Advent of Code 2017, Day 6: Memory Reallocation

#ruby #advent of code 2017

Part A

On Day 6 we are rebalancing memory banks. The rebalancing procedure find the bank with largest amount of blocks, removes all those blocks and redistributes them across all other banks. It moves to the next bank and drops one block there and then repeat the process.

We need to simulate this procedure given the initial state of our memory banks in input file. In the first part we need to tell how many loop iterations it takes to reach configuration that was previously seen before.

data = File.read("6.txt").split(/\s+/).map(&:to_i)
visited = { data => true }
steps = 0

while true
  max = data.max
  max_index = data.index(max)

  blocks = max
  data[max_index] = 0

  current = (max_index + 1) % data.size

  blocks.times do
    data[current] += 1
    current = (current + 1) % data.size
  end

  steps += 1

  if visited[data]
    puts steps
    break
  else
    visited[data] = true
  end
end

We have 16 memory banks and we store each configuration in visited hash. After seeing the same configuration we output number of loop iterations and break the loop.

Part B

In the second part we need to tell how many loop iterations it took between two same configurations were seen.

data = File.read("6.txt").split(/\s+/).map(&:to_i)
visited = { data => 0 }
steps = 0

while true
  max = data.max
  max_index = data.index(max)

  blocks = max
  data[max_index] = 0

  current = (max_index + 1) % data.size

  blocks.times do
    data[current] += 1
    current = (current + 1) % data.size
  end

  steps += 1

  if visited[data]
    puts steps - visited[data]
    break
  else
    visited[data] = steps
  end
end

This time in our visited hash we are storing the current loop iterations counter and when we see the same configuration we subtract current counter from the saved one.