I have an array of 16 squares and I would like to auto complete it with integers values depending of the position in the array and the vector TOP_RIGHT.
TOP_RIGHT = 3
# Build the array...
@top_right = Array.new(16, 0)
@top_right.each_index do |square|
@top_right[square] = square / TOP_RIGHT if (0...16).include?(square - TOP_RIGHT)
end
# Print the array...
i = 0
@top_right.each do |square|
puts if i % 4 == 0
print "#{square} "
i += 1
end
My code seems to be okay, but after testing the result is:
0 0 0 1
1 1 2 2
2 3 3 3
4 4 4 5
I would like to get this array:
0 0 0 0
1 1 1 0
2 2 1 0
3 2 1 0
Do you think it is possible, using array and simple Ruby methods?
Thanks, and happy end year!
Edit:
In the previous example, TOP_RIGHT is a vector like and its value is the number of cases that we can add or sub in order to go from the source square to the destination square (which is on top-right).
For example if I get this other vector: TOP, its value is 4 and the generated array can be:
# print_array(4)
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
...and if the vector is RIGHT, its value is -1 and the array can be:
# 开发者_如何转开发print_array(-1)
3 2 1 0
3 2 1 0
3 2 1 0
3 2 1 0
Isn't it a little beat tricky? :) I don't see how to process for designing a constructor which can build such arrays, by passing a value of a vector.
If you use an array to hold an array, and don't try to do it in a vector, it's not too bad:
#!/usr/bin/ruby1.8
top_right = 3
array_size = 4
a = (0...array_size).collect do |i|
(0...array_size).collect do |j|
[i, j].collect do |e|
top_right - e
end.min
end
end.reverse
a.each do |e|
p e
end
=> [0, 0, 0, 0]
=> [1, 1, 1, 0]
=> [2, 2, 1, 0]
=> [3, 2, 1, 0]
And if you really need the array squished into a vector, then:
v = a.flatten
精彩评论