views:

46

answers:

1

Hi,

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.

A: 

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
Wayne Conrad
Thank you very much, Wayne Conrad. I am really surprised to see this code... But if I replace the vector top_right = 3 by the vector top = 4, the returned array is not [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]] but [[1, 1, 1, 1], [2, 2, 2, 1], [3, 3, 2, 1], [4, 3, 2, 1]]. :)
Denis
Unless I'm missing something, top_right is a scalar, not a vector. Alright, I give: What is top_right supposed to represent that should cause the function to return a wildly different result for '4' than it does for '3'?
Wayne Conrad
Sorry because my problem is not very clear. I have edited my question with some examples. Thanks for your help Wayne.
Denis
It's doable. Copy the solution and then modify the copy so that it does TOP. Copy it again and modify it so it does RIGHT. Are you starting to see a common pattern? If you need to, code all four sides and all four corners until a common pattern emerges. Then code that pattern.
Wayne Conrad
Thanks. And Happy end of year.
Denis