transpose a 2d array in the ruby

The problem of transpose a 2d array in the ruby

This problem is about transpose a 2d array in the ruby programming language. The major constraint in this problem is that one cannot change the name and input or output parameters of the function. Another constraint is that the user cannot use the built-in transpose method. The long method for the transposition is as shown below: 

 

class Image 

def transpose
     @array.each_with_index do |row, row_index|
      row.each_with_index do |column, col_index|
        @array[row_index] = @array[col_index]
      end
    end 
  end 
end

image_transpose = Image.new([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])

print "Image transpose"
puts

image_transpose.output_image

puts "-----" 

image_transpose.transpose
image_transpose.output_image

puts "-----"

 

Solution

The transpose() function converts elements from the row into elements from the column and vice versa. This function produces an array that has been altered from the original. 

The above code is quite complex and is difficult to understand as well. So there is another approach to the same problem but in a quite easy manner. The code for the same is as follows:

 

class Image 

  def initialize(array)
    @array = array
  end

  def transpose
    _array = @array.dup
    @array = [].tap do |a|
      _array.size.times{|t| a << [] }
    end
    _array.each_with_index do |row, row_index|
      row.each_with_index do |column, col_index|
        @array[row_index][col_index] = _array[col_index][row_index]
      end
    end 
  end


end

image_transpose = Image.new([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
image_transpose.transpose

 

Another solution is to replace the transpose method in the ruby programming language. 

def transpose

 @array.first.zip(*@array[1..-1])

end

There is no obvious requirement for the (undefined) method output input. Of course, in order to give the instance variable @array a value, one will also need an initialize method.

The requirement that users cannot use Ruby’s built-in transpose method leads us to believe that programmers are being requested to enhance the transpose method’s implementation.

We suppose that one of the above-mentioned solutions will surely act as an optimal code for the above-mentioned problem. 

 

Also Read: show-doc not working in ruby pry

 

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *