01020304050607080910111213141516171819202122232425

Advent of Code

2017/6

Memory Reallocation

in C#

by encse

A debugger program here is having an issue: it is trying to repair a memory reallocation routine, but it keeps getting stuck in an infinite loop.

In this area, there are sixteen memory banks; each memory bank can hold any number of blocks. The goal of the reallocation routine is to balance the blocks between the memory banks.

Read the full puzzle.

using System.Collections.Generic;
using System.Linq;

namespace AdventOfCode.Y2017.Day06;

[ProblemName("Memory Reallocation")]
class Solution : Solver {

    public object PartOne(string input) => GetStepCount(Parse(input));

    public object PartTwo(string input) {
        var numbers = Parse(input);
        GetStepCount(numbers);
        return GetStepCount(numbers);
    }

    List<int> Parse(string input) => input.Split('\t').Select(int.Parse).ToList();

    int GetStepCount(List<int> numbers) {
        var stepCount = 0;
        var seen = new HashSet<string>();
        while (true) {
            var key = string.Join(";", numbers.Select(x => x.ToString()));
            if (seen.Contains(key)) {
                return stepCount;
            }
            seen.Add(key);
            Redistribute(numbers);
            stepCount++;
        }
    }

    void Redistribute(List<int> numbers) {
        var max = numbers.Max();
        var i = numbers.IndexOf(max);
        numbers[i] = 0;
        while (max > 0) {
            i++;
            numbers[i % numbers.Count]++;
            max--;
        }
    }
}

Please ☆ my repo if you like it!

© 2025 Advent of Code is a registered trademark in the US Images provided by Bing image creator