-2
double_array = [
  ["0", "0", "0", "0", "0"],
  ["0", "0", "0", "0", "0"],
  ["0", "0", "0", "0", "0"],
  ["0", "0", "0", "0", "0"],
  ["0", "0", "0", "0", "0"],
]

Let's say the digits in this array change like so:

double_array = [
      ["1", "0", "0", "0", "0"],
      ["0", "1", "0", "0", "0"],
      ["0", "0", "1", "0", "0"],
      ["0", "0", "0", "1", "0"],
      ["0", "0", "0", "0", "0"],
    ]

How would I get be able to detect on that with some kind of if statement? Something like if there are four in a row diagonally do [insert action here].

The same goes for if it were vertically or horizontally like so:

double_array = [
      ["1", "0", "0", "0", "0"],
      ["1", "0", "0", "0", "0"],
      ["1", "0", "0", "0", "0"],
      ["1", "0", "0", "0", "0"],
      ["0", "1", "1", "1", "1"],
    ]

I'd prefer the least complex way possible.

  • 2
    Show us what have you tried, are you stuck at some point ? – Subash Mar 19 '18 at 00:18
  • Not clear what you mean by "has the same value up to certain point". – sawa Mar 19 '18 at 01:38
  • Like if I want to check the values of double_array[3] (the fourth one down) from 0 to 3, for example. Or if I want to check index 0 for each array inside the double array. – Dollarluigi Mar 19 '18 at 01:53
  • What do you mean by same values up to certain point? `double_array[3]` denotes fourth row, so do you want all values in fourth row? Question is not quite clear. Please provide more example as to what you're expecting, also add some code that you tried. – Surya Mar 19 '18 at 08:24
  • Yes I was referring to the fourth row, but I was also referring to the first four indexes in that row. – Dollarluigi Mar 19 '18 at 16:33
  • I'll try this one more time and honestly I really don't appreciate how this ended up being changed into something other than what I was actually asking for. – Dollarluigi Mar 20 '18 at 04:20

1 Answers1

0
last_row_ndx = double_array.size-1
  #=> 4
last_col_ndx = double_array.first.size-1
  #=> 4

(0..last_row_ndx).each_with_object(Hash.new { |h,k| h[k] = [] }) do |i,h|
  (0..last_col_ndx).each do |j|
    v = double_array[i][j]
    h[v] << [[i-1,j], [i,j]] if i > 0 && v == double_array[i-1][j]
    h[v] << [[i,j-1], [i,j]] if j > 0 && v == double_array[i][j-1]
  end
end
  #=> {"1"=>[[[0, 0], [1, 0]], [[1, 0], [1, 1]], [[1, 0], [2, 0]], 
  #          [[2, 0], [3, 0]], [[3, 0], [3, 1]], [[2, 2], [3, 2]],
  #          [[3, 1], [3, 2]], [[3, 2], [3, 3]]], 
  #    "4"=>[[[0, 3], [1, 3]], [[1, 3], [2, 3]]],
  #    "0"=>[[[0, 4], [1, 4]], [[1, 4], [2, 4]], [[2, 4], [3, 4]],
  #          [[4, 0], [4, 1]], [[4, 1], [4, 2]], [[4, 2], [4, 3]],
  #          [[3, 4], [4, 4]], [[4, 3], [4, 4]]]}
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100