01020304050607080910111213141516171819202122232425

Advent of Code

2018/9

Marble Mania

in C#

by encse

You talk to the Elves while you wait for your navigation system to initialize. To pass the time, they introduce you to their favorite marble game.

The Elves play this game by taking turns arranging the marbles in a circle according to very particular rules. The marbles are numbered starting with 0 and increasing by 1 until every marble has a number.

Read the full puzzle.

using System.Linq;
using System.Text.RegularExpressions;

namespace AdventOfCode.Y2018.Day09;

[ProblemName("Marble Mania")]
class Solution : Solver {

    public object PartOne(string input) => Solve(input, 1);

    public object PartTwo(string input) => Solve(input, 100);

    long Solve(string input, int mul) {

        var match = Regex.Match(input, @"(?<players>\d+) players; last marble is worth (?<points>\d+) points");
        var players = new long[int.Parse(match.Groups["players"].Value)];
        var targetPoints = int.Parse(match.Groups["points"].Value) * mul;

        var current = new Node { value = 0 };
        current.left = current;
        current.right = current;

        var points = 1;
        var iplayer = 1;
        while (points <= targetPoints) {

            if (points % 23 == 0) {
                for (var i = 0; i < 7; i++) {
                    current = current.left;
                }

                players[iplayer] += points + current.value;

                var left = current.left;
                var right = current.right;
                right.left = left;
                left.right = right;
                current = right;

            } else {
                var left = current.right;
                var right = current.right.right;
                current = new Node { value = points, left = left, right = right };
                left.right = current;
                right.left = current;
            }

            points++;
            iplayer = (iplayer + 1) % players.Length;
        }

        return players.Max();
    }
}

class Node {
    public int value;
    public Node left;
    public Node right;
}

Please ☆ my repo if you like it!

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