Why are the elements in the mass not changing?



  • There's a task I've decided in theory, but it doesn't change the meaning of the temp. What's the nail?

    =begin 
    Заполнить квадратную матрицу размера n на n натуральными
    числами от 1 до n**2 в указанном порядке:
    
        | 1 2 3 |
        | 6 5 4 |
        | 7 8 9 |
    

    =end

    glob_arr = []
    temp = []

    puts "Введите n"
    n = gets.chomp.to_i
    for i in 1..n
    temp<<i
    end

    for i in 0..n-1
    if i%2==0
    glob_arr << temp
    else
    glob_arr << temp.reverse
    end
    temp.reverse.each{ |e| e+=1 }
    end
    glob_arr.each { |e| puts e.to_s }



  • May be as follows:

    glob_arr = []
    

    puts "Введите n"
    n = gets.chomp.to_i
    temp = Array.new(n, 0).fill { |i| i + 1 }

    n.times do |i|
    if i.even?
    glob_arr << temp.dup
    else
    glob_arr << temp.reverse
    end
    glob_arr[i].map!{ |e| e += n * i }
    end

    glob_arr.each { |e| puts e.to_s }

    The result is the following conclusion:

    Введите n
    3
    [1, 2, 3]
    [6, 5, 4]
    [7, 8, 9]

    The point is, you're elements of the mass. glob_arr Appropriation of the same mass temp♪ In ruby all is the object and the objects are transmitted by reference. By changing one line of the matrix, you will touch all three lines. That's better. temp cloning, for example, by means of a method dup - Then the rows of the matrix will be different sets that can be transformed independently.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2