From 1d39f15e9c106a0d2b492793256ce086b828db79 Mon Sep 17 00:00:00 2001 From: Ngoc Le Date: Thu, 2 May 2019 00:28:49 -0700 Subject: [PATCH] added solution --- lib/matrix_convert_to_zero.rb | 55 ++++++++++++++++++++++++++-- specs/matrix_convert_to_zero_spec.rb | 11 +++--- 2 files changed, 58 insertions(+), 8 deletions(-) diff --git a/lib/matrix_convert_to_zero.rb b/lib/matrix_convert_to_zero.rb index 4fb139c..ca2d608 100644 --- a/lib/matrix_convert_to_zero.rb +++ b/lib/matrix_convert_to_zero.rb @@ -3,8 +3,57 @@ # 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: ? +#Approach 1: +# Time complexity: O(n^3) 3 nested loops +# Space complexity: O(n^2) n is the number of rows and columns in the matrix being cloned + +def matrix_convert_to_zero_n_3(matrix) + clone = matrix.map(&:dup) + rows = matrix.length + columns = matrix[0].length + rows.times do |i| + columns.times do |j| + if matrix[i][j] == 0 + columns.times do |jj| + clone[i][jj] = 0 + end + rows.times do |ii| + clone[ii][j] = 0 + end + end + end + end + rows.times do |i| + columns.times do |j| + matrix[i][j] = clone[i][j] + end + end +end + +#Approach 2: +# Time complexity: O(n^2) 2 nested loops +# Space complexity: O(n) n is the number of affected rows and columns def matrix_convert_to_zero(matrix) - raise NotImplementedError + affected_rows = [] + affected_columns = [] + rows = matrix.length + columns = matrix[0].length + rows.times do |i| + columns.times do |j| + if matrix[i][j] == 0 + affected_rows << i + affected_columns << j + end + end + end + affected_rows.each do |i| + columns.times do |j| + matrix[i][j] = 0 + end + end + affected_columns.each do |j| + rows.times do |i| + matrix[i][j] = 0 + end + end end diff --git a/specs/matrix_convert_to_zero_spec.rb b/specs/matrix_convert_to_zero_spec.rb index a21b0a6..9ef8e21 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| @@ -47,8 +47,9 @@ def verify_matrix(matrix, rows_array, columns_array) columns_array = [3, 4] # method call + p matrix matrix_convert_to_zero(matrix) - + p matrix # validation verify_matrix(matrix, rows_array, columns_array) end