Advent of Code 2017, Day 5: A Maze of Twisty Trampolines, All Alike

#ruby #advent of code 2017

Part A

On Day 5 we are trying to escape a maze. In our input array we have jump offsets that points to different elements of the array. After each jump we need to increase the current offset. Our goal is to tell how many jumps we need to do to jump outside of our array.

data = File.readlines("5.txt", chomp: true).map(&:to_i)

index = 0
steps = 0

while true
  offset = data[index]
  data[index] += 1

  index += offset
  steps += 1

  if index < 0 || index >= data.size
    break
  end
end

puts steps

Part B

In the second part if offset is greater or equal 3 we need to decrease it by 1. Otherwise we increase it by 1 as in the first part.

data = File.readlines("5.txt", chomp: true).map(&:to_i)

index = 0
steps = 0

while true
  offset = data[index]
  if offset >= 3
    data[index] -= 1
  else
    data[index] += 1
  end

  index += offset
  steps += 1

  if index < 0 || index >= data.size
    break
  end
end

puts steps