Matrix Search
August 17, 2018
Today’s exercise is a simple task in matrix manipulation. Given a matrix in which the rows are ordered but the columns or not, efficiently search for a specific item in the matrix. For instance, given the matrix
2 5 8 1 4 7 3 6 9
a search for 6 finds it in row 2 column 1, a search for 8 finds it in row 0 column 2, and a search for 0 fails.
Your task is to write a program that searches a matrix. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Here’s a solution in C.
Output:
Klong version 2
[sourcecode lang="css"]
.comment(“end-of-comment”)
[n s] – Set up 2 local variables
s::#x – Get size of matrix (Number of row/columns)
(,/:~x) – Flatten matrix into 1 row
?y – Find second parameter in flattened matrix
n::… – Assign location of 2nd parameter to n
If not found, assign []
:[0=#n; – If 2nd parameter not found (Size of parameter ([]) is 0)
[-1 -1] – True –> return [-1 -1]
False
n::n@0 – Get element in flattened matrix and assign to n
(…)!s – Get column by getting remainer of n and s
(_n%s) – Get row by integer dividing element by s
(!n…),(n::…) – Return list of row and column
ms::{…} – Make function and name it ms
.p(…) – Print argument
‘!10 – Run function against each element of list from 0 to 9
end-of-comment
Examples:
{{.p(x,” –> “,,ms([[2 5 8][1 4 7][3 6 9]]; x))}’!10}();””
[0 –> [-1 -1]]
[1 –> [1 0]]
[2 –> [0 0]]
[3 –> [2 0]]
[4 –> [1 1]]
[5 –> [0 1]]
[6 –> [2 1]]
[7 –> [1 2]]
[8 –> [0 2]]
[9 –> [2 2]]
“”
Klong version 3
@programmingpraxis: Please delete Klong version 2. Thanks.
Mumps version