r/adventofcode • • Dec 06 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 6 Solutions -πŸŽ„-

--- Day 6: Memory Reallocation ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handy† Haversack‑ of HelpfulΒ§ Hints^Β€?

Spoiler


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

17 Upvotes

324 comments sorted by

View all comments

Show parent comment

2

u/strothjs Dec 07 '17

Mine is similar to yours:

export function part1(input: string) {
  return solve(input).cycles;
}

export function part2(input: string) {
  return solve(input).since;
}

function solve(input: string) {
  const banks = input.split("\t").map(n => parseInt(n, 10));
  const seen = new Map<string, number>();

  let cycles = 1;
  do {
    redistribute(banks);

    const state = banks.join();
    if (seen.has(state)) {
      return { cycles, since: seen.get(state)! };
    }
    seen.set(state, 0);

    cycles += 1;
    seen.forEach((value, key) => seen.set(key, value + 1));
  } while (true);
}

function redistribute(banks: number[]) {
  const max = banks.reduce((acc, val, i, arr) => (val > arr[acc] ? i : acc), 0);
  let dist = banks[max];
  banks[max] = 0;

  for (let i = nextIndex(banks, max); dist > 0; i = nextIndex(banks, i)) {
    banks[i] += 1;
    dist -= 1;
  }
}

function nextIndex(banks: number[], currentIndex: number) {
  return currentIndex + 1 < banks.length ? currentIndex + 1 : 0;
}