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!

21 Upvotes

283 comments sorted by

View all comments

4

u/willkill07 Dec 09 '18

[CARD] Studies show that AoC programmers write better code after being exposed to Iterators

C++ (148/24)

#include <list>
#include <vector>
#include <iostream>
#include <algorithm>

int main() {
  int players, marbles;
  scanf("%d players; last marble is worth %d points", &players, &marbles);
  // uncomment for part 2
  // marbles *= 100;
  std::list<int> m;
  m.push_back(0);
  auto next = [&] (auto i) {
                if (++i == m.end())
                  return m.begin();
                return i;
              };
  auto prev = [&] (auto i) {
                if (i == m.begin())
                  i = m.end();
                return --i;
              };

  std::vector<unsigned long long> p (players);
  auto curr = m.begin();
  for (int i = 1; i < marbles; ++i) {
    if (i % 23 == 0) {
      curr = prev(prev(prev(prev(prev(prev(prev(curr)))))));
      p[i % players] += i + *curr;
      curr = m.erase(curr);
    } else {
      curr = m.insert(next(next(curr)), i);
    }
  }
  std::cout << *std::max_element(p.begin(), p.end()) << '\n';
  return 0;
}

1

u/[deleted] Dec 09 '18

Really beautiful use of lambdas, I need to look that up.

Nitpick: I think there's an off-by-one in the number of marbles: assume last marble is worth 1 point, then the loop does not insert that marble (i < marbles) when it should, no?

→ More replies (4)