1

I am trying to figure out how I can refactor my code below so that I can iterate through the array without using the "index1" and "index2" variables to keep track of my progress.

  board.each do |cell|
    diag1 << cell[index1]
    diag2 << cell[index2]
    index1 += 1
    index2 -= 1
  end

I tried using .each_with_index (see below), but I'm not sure how to increment my values for "i".

  board.each_with_index do |cell, i|
    diag1 << cell[i += 1]
    diag2 << cell[i -= 1]
  end

The array "board" is an n*n array of a tic-tac-to game that is at least 3x3 in size or larger and the block of code is supposed to check to see if there is a diagonal match. Thanks in advance!

Edit: Figured it out. Here is the working code snippet:

  board.each_with_index do |cell, i|
    diag1 << cell[i]
    diag2 << cell[-(i +1)]
  end
7
  • ... i + 1 and i - 1? That will be broken, though, because you'll wrap around. Commented Oct 23, 2014 at 14:45
  • What is board, what is cell (shouldn't it be rather row)? What is the input (board) and what is an expected output? Commented Oct 23, 2014 at 14:47
  • An example of board might be [["x", " ", " ", " "], [" ", "x", " ", " "], [" ", " ", "x", " "], [" ", " ", " ", "x"]] with the expected output of diag1 to be xxxx, which is passed through another part of the code to confirm that it's a win. Here is the complete working code I have now for reference. gist.github.com/danielbonnell/6769fb41e2f5f4603fd9 Commented Oct 23, 2014 at 14:55
  • 1
    Yeah, I did. But I wasnt happy with my answer so I removed it. Commented Oct 23, 2014 at 15:13
  • 1
    Are you aware that your current check method will return true for OXXX? Commented Oct 23, 2014 at 15:20

1 Answer 1

1

You can do:

diag1, diag2 = board.map.with_index {|row, i| [row[i],row[-i-1]]}.transpose

The main trick I'm using here is array's way of interpret negative argument. array[-1] always means the last element of an array, array[-2] denotes second last etc.

Sign up to request clarification or add additional context in comments.

1 Comment

I like this even more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.