Zeroing A Matrix
February 17, 2017
Our solution first scans for zero elements, then goes back and makes changes. The rows and columns that need to be zeroed are collected in sets rows
and cols
, which are lists to which duplicate elements are not added:
(define (adjoin x xs) (if (member x xs) xs (cons x xs)))
(define (zero mtrx) (let ((rows (list)) (cols (list)) (n-rows (matrix-rows mtrx)) (n-cols (matrix-cols mtrx))) (for (row 0 n-rows) (for (col 0 n-cols) (when (zero? (matrix-ref mtrx row col)) (set! rows (adjoin row rows)) (set! cols (adjoin col cols))))) (do ((rows rows (cdr rows))) ((null? rows)) (for (col 0 n-cols) (matrix-set! mtrx (car rows) col 0))) (do ((cols cols (cdr cols))) ((null? cols)) (for (row 0 n-rows) (matrix-set! mtrx row (car cols) 0))) mtrx))
Here’s an example:
> (zero '#(#(0 2 3 4 5) #(1 0 3 4 5) #(1 2 0 4 5) #(1 2 3 0 5) #(1 2 3 4 0))) #(#(0 0 0 0 0) #(0 0 0 0 0) #(0 0 0 0 0) #(0 0 0 0 0) #(0 0 0 0 0))
You can run the program at http://ideone.com/X7roST.
In Python using numpy.
A solution in Racket.