Skip to content

Instantly share code, notes, and snippets.

@tongrhj
Created January 13, 2017 04:55
Show Gist options
  • Save tongrhj/29fcb988ad64a3f3925c2482cbdc7357 to your computer and use it in GitHub Desktop.
Save tongrhj/29fcb988ad64a3f3925c2482cbdc7357 to your computer and use it in GitHub Desktop.
boolean-matrix-answer-ruby.rb
=begin
Given a 2-dimensional matrix mat[M][N] of size M X N containing only the values 0 and 1, modify it such that if a matrix cell mat[i][j] is 1 then all the cells of ith row and jth column are set to 1 as well.
Example 1
The matrix
1 0
0 0
should be changed to following
1 1
1 0
Example 2
The matrix
0 0 0 0
0 0 1 0
1 0 0 0
0 0 0 0
should be changed to following
1 0 1 0
1 1 1 1
1 1 1 1
1 0 1 0
You have 15 minutes to do this task.
=end
test_one = [[1, 0], [0, 0]].freeze
result_one = [[1, 1], [1, 0]].freeze
test_two = [[0,0,0,0],[0,0,1,0],[1,0,0,0],[0,0,0,0]].freeze
result_two = [[1,0,1,0],[1,1,1,1],[1,1,1,1],[1,0,1,0]].freeze
test_suite = [
[test_one, result_one],
[test_two, result_two]
]
def print_matrix(matrix)
matrix.each do |row|
puts(row.inspect)
end
end
def flip_row (matrix, row_number)
matrix[row_number].map! {|cell| 1 }
matrix
end
def flip_col (matrix, col_number)
matrix.each_with_index do |row, row_number|
matrix[row_number][col_number] = 1
end
matrix
end
def transform(matrix)
# Deep copy hack, potential pitfall
mtx = Marshal.load(Marshal.dump(matrix))
matrix.each_with_index do |row, row_number|
row.each_with_index do |cell, col_number|
if cell == 1
mtx = flip_row(mtx, row_number)
mtx = flip_col(mtx, col_number)
end
end
end
mtx
end
test_suite.each do |test|
puts('----------------------')
puts('Input:')
print_matrix(test[0])
puts('Expected Output:')
print_matrix(test[1])
puts('Actual Output:')
test_result = transform(test[0])
print_matrix(test_result)
puts ("TEST RESULT: " + (test[1] === test_result and 'PASSED' or 'FAILED'))
puts('----------------------')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment