def diff(magic_square,s) d = 0 3.times do |i| 3.times do |j| d += (magic_square[i][j] - s[i][j]).abs end end d end s = Array.new 3.times do |i| s[i] = gets.strip.split(" ").map(&:to_i) end a = [4,9,2,7,6,1,8,3] sum = -1 8.times do magic_square = [[a[0],a[1],a[2]],[a[7],5,a[3]],[a[6],a[5],a[4]]] [diff(magic_square,s),diff(magic_square.transpose,s)].each do |d| if(d < sum || sum == -1) sum = d end end a.rotate!(2) end puts sum