diff --git a/lib/matrix_convert_to_zero.rb b/lib/matrix_convert_to_zero.rb index 4fb139c..4c9a90a 100644 --- a/lib/matrix_convert_to_zero.rb +++ b/lib/matrix_convert_to_zero.rb @@ -3,8 +3,35 @@ # 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: the time complexity is O(n*m) where n is the number of rows in the matrix and m is the number of columns in the matrix because I have two nested loops O(2*n*m), which dropping the constant reduces to O(n*m) +# Space complexity: space complexity is O(n) where n is the larger number of rows or columns. This is because a hash is created where the rows are keys and columns are values def matrix_convert_to_zero(matrix) - raise NotImplementedError + num = 0 + pos = Hash.new + rows = matrix.size + columns = matrix[0].size + + rows.times do |row| + columns.times do |col| + if matrix[row][col] == 0 + if pos.include? row + num += 1 + pos["row" + num.to_s] = col + else + pos[row] = col + end + end + end + end + rows.times do |row| + columns.times do |col| + if pos.include? row + matrix[row][col] = 0 + end + if pos.values.include? col + matrix[row][col] = 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..b563e9a 100644 --- a/specs/matrix_convert_to_zero_spec.rb +++ b/specs/matrix_convert_to_zero_spec.rb @@ -1,11 +1,11 @@ -require 'minitest/autorun' -require 'minitest/reporters' -require_relative '../lib/matrix_convert_to_zero' +require "minitest/autorun" +require "minitest/reporters" +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| @@ -129,6 +129,7 @@ def verify_matrix(matrix, rows_array, columns_array) matrix[0][3] = 0 # row 0, column 1 matrix[0][4] = 0 # row 1, column 1 matrix[2][1] = 0 # row 2, column 1 + p matrix rows_array = [0, 2] columns_array = [1, 3, 4]