ruby - Assigning values to a 2D array using "each" method -


i'm trying transpose [[0, 1, 2], [3, 4, 5], [6, 7, 8]]. [[2, 5, 8], [2, 5, 8], [2, 5, 8]].

i can see happening line p transposed_arr not understand why happening. @ every iteration changes every row instead of one.

def my_transpose(arr)   # number of rows   m = arr.count    #number of columns   n = arr[0].count    transposed_arr = array.new(n, array.new(m))    # loop through rows   arr.each_with_index |row, index1|        # loop through colons of 1 row       row.each_with_index |num, index2|            # swap indexes transpose initial array           transposed_arr[index2][index1] = num           p transposed_arr       end   end   transposed_arr end 

you need make 1 wee change , method work fine. replace:

transposed_arr = array.new(n, array.new(m)) 

with:

transposed_arr = array.new(n) { array.new(m) } 

the former makes transposed_arr[i] same object (an array of size m) i. latter creates separate array of size m each i

case 1:

transposed_arr = array.new(2, array.new(2)) transposed_arr[0].object_id   #=> 70235487747860  transposed_arr[1].object_id   #=> 70235487747860 

case 2:

transposed_arr = array.new(2) { array.new(2) } transposed_arr[0].object_id   #=> 70235478805680  transposed_arr[1].object_id   #=> 70235478805660 

with change method returns:

[[0, 1, 2],  [3, 4, 5],  [6, 7, 8]] 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -