diff --git a/lib/matrix_convert_to_zero.rb b/lib/matrix_convert_to_zero.rb index 4fb139c..10208ae 100644 --- a/lib/matrix_convert_to_zero.rb +++ b/lib/matrix_convert_to_zero.rb @@ -3,8 +3,27 @@ # If any number is found to be 0, the method updates all the numbers in the # corresponding row as well as the corresponding column to be 0. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n^2) where n is the width of the matrix. Or O(w*h), where w is the width, and h is the height. +# Space complexity: O(1) constant, regardless of the size of the matrix, a constant number of fixed sixed variables are needed. def matrix_convert_to_zero(matrix) - raise NotImplementedError + rows = matrix.size + columns = matrix[0].size + rows.times do |row| + columns.times do |column| + if matrix[row][column] == 0 + matrix[row][column] = 2 + end + end + end + + rows.times do |row| + columns.times do |column| + if matrix[row][column] == 2 + columns.times { |i| matrix[row][i] = 0 unless matrix[row][i] == 2 } + rows.times { |i| matrix[i][column] = 0 unless matrix[i][column] == 2 } + matrix[row][column] = 0 + end + end + end + return matrix end diff --git a/specs/matrix_convert_to_zero_spec.rb b/specs/matrix_convert_to_zero_spec.rb index a21b0a6..46cb3c4 100644 --- a/specs/matrix_convert_to_zero_spec.rb +++ b/specs/matrix_convert_to_zero_spec.rb @@ -1,11 +1,12 @@ -require 'minitest/autorun' -require 'minitest/reporters' -require_relative '../lib/matrix_convert_to_zero' +require "minitest/autorun" +require "minitest/reporters" +require "minitest/pride" +require_relative "../lib/matrix_convert_to_zero" # helper method for creating and initializing a matrix with all 1s def initialize_matrix(rows, columns) # create the matrix using the rows and columns - matrix = Array.new(rows){Array.new(columns)} + matrix = Array.new(rows) { Array.new(columns) } # initialize the matrix rows.times do |row|