Sujet : Re: matrix operations
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.lispDate : 03. Jul 2024, 03:41:20
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20240702191750.748@kylheku.com>
References : 1
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2024-07-03, B. Pym <
No_spamming@noWhere_7073.org> wrote:
Barry Margolin wrote:
>
Zachary Turner <ztur...@bindview.com> wrote:
I've got a 3x3 matrix, stored as ((r1c1 r1c2 r1c3) (r2c1 r2c2 r2c3) (r3c1
r3c2 r3c3)). I want to check if any of the columns have the same three
elements. It's easy for rows, I can just use
(or
(every #'equal (car matrix))
(every #'equal (cadr matrix))
(every #'equal (caddr matrix)))
If it didn't have to scale to larger matrices, I'd probaby just do:
(defun has-column-3x3 (matrix)
(if-match @(or ((@x . @nil)
(@x . @nil)
(@x . @nil))
((@nil @x . @nil)
(@nil @x . @nil)
(@nil @x . @nil))
((@nil @nil @x)
(@nil @nil @x)
(@nil @nil @x)))
matrix
t))
(defun has-column-3x3 (matrix)
(if-match @(or ((@x @x @xl) . @nil)
(@nil (@x @x @x) . @nil)
(@nil @nil (@x @x @x)))
matrix
t))
(defun has-diagonal-3x3 (matrix)
(if-match @(or ((@x . @nil)
(@nil @x . @nil)
(@nil @nil @x))
((@nil @nil @x)
(@nil @x . @nil)
(@x . @nil)))
matrix
t))
If we want to test for a specific value of x (e.g. #\X or #\O
in Tic Tac Toe), we just add that as a parameter
(defun has-diagonal-3x3 (matrix x)
(if-match @(or ((@x . @nil)
(@nil @x . @nil)
(@nil @nil @x))
((@nil @nil @x)
(@nil @x . @nil)
(@x . @nil)))
matrix
t))
The pattern matcher will substitute the value of the existing
lexical x for the pattern variable @x.
2> (has-diagonal-3x3 '((x o o)
(o x _)
(_ _ x)) 'x)
t
3> (has-diagonal-3x3 '((x o o)
(o _ _)
(_ _ x)) 'x)
nil
4> (has-diagonal-3x3 '((x o o)
(o o x)
(o x x)) 'x)
nil
5> (has-diagonal-3x3 '((x o o)
(o o x)
(o x x)) 'o)
t
Backquote notation can be used.
(defun has-diagonal-3x3 (matrix x)
(if-match @(or ^((,x . ,nil)
(,nil ,x . ,nil)
(,nil ,nil ,x))
^((,nil ,nil ,x)
(,nil ,x . ,nil)
(,x . ,nil)))
matrix
t))
-- TXR Programming Language: http://nongnu.org/txrCygnal: Cygwin Native Application Library: http://kylheku.com/cygnalMastodon: @Kazinator@mstdn.ca