Dynamic programming: Given a matrix consisting of 0's and 1's, find the maximum size sub-matrix consisting of only 1's.
-
Unless you already know, learn what the terms matrix and sub-matrix mean. What is a maximum size sub-matrix? How can you calculate it on paper? Try out a few examples on paper with a small matrix.
-
How can you implement a matrix in Ruby? Don't use a class for this, yet. Try to express this using arrays, hashes, or enumerables, or all of them.
-
Try to give two ways to program the solution. Which of your solutions is faster? Which requires more memory? Explain your answers.
It seems that there are two widespread definitions for submatrix
, the one provided on Wikipedia and the one provided on Math World. This code uses the definition from Wikipedia.
This solution implements two slightly different versions (iterative vs recursive), that use the same logic to remove rows or columns where the first 0
is found --there is almost no difference.
The matrix is represented as an array of arrays, each of which contain 0
or 1
.
To find zeros, a simple linear search is run sequentially over each inner array and, when the first 0 is found, the row and column indexes are returned.
Then, the program decides if is better to remove the row or the column, based on the following criteria:
`IF` there are more ones on the row than in the column, remove the column.
`ELSE IF` there are less ones on the row that in the column, remove the row.
`ELSE`
`IF` there are more zeros on the column than in the row, remove the column.
`ELSE` remove the row.
When no more zeros are found, the program assumes the maximum unit submatrix has been found.
Validations can be run on the provided array if desired.
Thought that the recursive version would be faster, but seems that the iterative version is faster.
Guess the program may be improved by using a better search algorithm or, per harps, a more sophisticated structure to represent the matrix.
I was also tempted to include the code as an Array refinement...
Sample stats for 10,000 iterations with a 10x10 matrix running benchmark.rb
.
Rehearsal -----------------------------------------------------------------------
iterative submatrix 1.890000 0.000000 1.890000 ( 1.890481)
recursive submatrix 2.360000 0.000000 2.360000 ( 2.361244)
iterative submatrix with validation 2.110000 0.000000 2.110000 ( 2.116418)
recursive submatrix with validation 2.550000 0.000000 2.550000 ( 2.543762)
-------------------------------------------------------------- total: 8.910000sec
user system total real
iterative submatrix 1.890000 0.000000 1.890000 ( 1.888168)
recursive submatrix 2.320000 0.000000 2.320000 ( 2.317262)
iterative submatrix with validation 2.110000 0.000000 2.110000 ( 2.110418)
recursive submatrix with validation 2.530000 0.000000 2.530000 ( 2.534197)
- Add specs for both versions by sharing examples.
- Add validaton to reject arrays that contains only zeros.