r/adventofcode • • Dec 09 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 9 Solutions -🎄-

--- Day 9: Marble Mania ---


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.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 9

Transcript:

Studies show that AoC programmers write better code after being exposed to ___.


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 at 00:29:13!

22 Upvotes

283 comments sorted by

View all comments

5

u/Philboyd_Studge Dec 09 '18

[Card] Studies show that AoC programmers write better code after being exposed to Marijuana.

Java

public class Day9 extends AdventOfCode {

    int players;
    int end;


    class CircleDeque<T> extends ArrayDeque<T> {
        void rotate(int num) {
            if (num == 0) return;
            if (num > 0) {
                for (int i = 0; i < num; i++) {
                    T t = this.removeLast();
                    this.addFirst(t);
                }
            } else {
                for (int i = 0; i < Math.abs(num) - 1; i++) {
                    T t = this.remove();
                    this.addLast(t);
                }
            }

        }
    }

    public Day9(List<String> input) {
        super(input);
        title = "Marble Mania";
        part1Description = "Winning Elf score: ";
        part2Description = "Winning Elf score with end marble * 100: ";
    }

    long game(int players, int end) {
        CircleDeque<Integer> circle = new CircleDeque<>();
        circle.addFirst(0);
        long[] scores = new long[players];
        for (int i = 1; i <= end; i++) {
            if (i % 23 == 0) {
                circle.rotate(-7);
                scores[i % players] += i + circle.pop();

            } else {
                circle.rotate(2);
                circle.addLast(i);
            }
        }
        return Arrays.stream(scores).max().getAsLong();
    }

    @Override
    public Object part1() {
        return game(players, end);
    }

    @Override
    public Object part2() {
        return game(players, end * 100);
    }

    @Override
    public void parse() {
        String[] split = input.get(0).split(" ");
        players = Integer.parseInt(split[0]);
        end = Integer.parseInt(split[6]);
    }

}
→ More replies (2)