0

Basically I'm looping through a matrix of arrays adding up the columns, but it stops right before the 2nd iteration of the 9.times loop. If I change y = 1 it will perform the action and stop at y = 2 and so on.

def new_feature(board)
  x=0
  y=0
  vertical = []
    while y < 9
      9.times do
        vertical << board[x][y]
        x += 1
      end
     puts vertical.reduce(:+)
     vertical = []
     y += 1 
    end
end

1 Answer 1

3

You never reset x back to 0, so in the second while iteration your x starts with 9 where it finished last time, not 0. This makes board[9], which is presumably out of bounds and thus nil; and then nil[1] crashes your code.

Note that you can write 9.times do |x| ... end to have x count from 0 to 8 without any manual counting, since times passes the current iteration number into the block.

Also, a more Rubyish way to sum columns:

board.transpose.map { |row| row.reduce(&:+) }
Sign up to request clarification or add additional context in comments.

Comments

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.