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

64

u/[deleted] Dec 09 '18 edited Dec 09 '18

Deque the halls -- ho ho ho!

Python 3, about 2 seconds total for parts 1 and 2 combined on my machine:

from collections import deque, defaultdict

def play_game(max_players, last_marble):
    scores = defaultdict(int)
    circle = deque([0])

    for marble in range(1, last_marble + 1):
        if marble % 23 == 0:
            circle.rotate(7)
            scores[marble % max_players] += marble + circle.pop()
            circle.rotate(-1)
        else:
            circle.rotate(-1)
            circle.append(marble)

    return max(scores.values()) if scores else 0

9

u/aminm17 Dec 09 '18

Would you mind walking me through your thought process? I tried solving it in a naive kind of way and a deque did not even cross my mind! Was wondering what is the correct way of thinking about such problems?

13

u/[deleted] Dec 09 '18 edited Dec 09 '18

A "deque" is short for "double-ended queue," which Python implements internally as a doubly-linked list in C (also why it's generally faster than trying to make your own).

Whenever you're moving around a circle and adding/removing items as you go, a deque is oftentimes a good fit -- especially since it can do all these things in constant time by moving pointers around.

3

u/__dkp7__ Dec 09 '18

I saw some solutions using rotate(2) for else part and -7 for if. How does both the solution works? It would be helpful if you could explain rotate(2) part.

4

u/ayylongqueues Dec 09 '18

My solution uses 7, and -2, for the rotations respectively. I assume it's because OP appends his nodes to the "end" of the queue after one clockwise rotation, whereas I rotate twice clockwise and append to the left. The position you append to is the same. But OP uses one less rotation for every append than I do, if it makes sense.

→ More replies (4)
→ More replies (2)
→ More replies (1)

2

u/tacothecat Dec 09 '18

For me it was having the marbles being in a circle. Having the rotate op makes it very easy to keep track of your current position. I tried in R at first but gave up and made almost an identical solution to OP in python.

→ More replies (1)

3

u/K_05 Dec 09 '18

Using a deque is pretty smart (and holiday spirit!). I did something similar, but instead of just returning max(scores.values()), I set it to a variable, and have it loop for marble in xrange(last_marble + 1, (last_marble * 100) + 1) again because the game is just being continued for part 2 and then returned both maxes. It's not as flexible/ modular, but it's how I initially saw the problem, and probably less time, since it doesn't need to recalculate.

8

u/[deleted] Dec 09 '18

The calculation of part 1 is maybe 1% of the overall time the program runs

3

u/zebington Dec 09 '18

I guess there's no point point posting my code, seeing as mine only differs in names and not doing the scores exists check at the end. I even passed the arguments in the same order! I guess this whole pythonic idea really is true.

2

u/tobiasvl Dec 09 '18

There should be one-- and preferably only one --obvious way to do it.

Although that way may not be obvious at first unless you're Dutch.

3

u/glad0s98 Dec 09 '18 edited Dec 09 '18

now while im waiting for my code that uses only regular lists to complete, I reeally wish I had known these queues and linked lists are a thing. Never even heard of them before

2

u/thomasahle Dec 09 '18

There's a nice overview over the complexities of different operations on different Python data-structures in the Python Wiki: https://wiki.python.org/moin/TimeComplexity

→ More replies (3)

3

u/dorfsmay Dec 09 '18

For python sake!!!! This is crazy short and really elegant.

I wrote a version with a python list. It's slow, gets the fan kicking, but return the right answer in ~ 5 minutes for part 1. I run all the tests included in the problem in 5 sec.

Being too slow and everybody saying the point of part 2 is to optimize your code by writing your own linked list, I implemented my own double linked list with... a class (each node is an object linking to the previous and next node). It works but it takes 26 sec to run all the tests now :(

→ More replies (7)

2

u/[deleted] Dec 09 '18

Very interesting approach. It is ~8 times faster than my implementation with double linked lists. Altough it is a bit difficult to understand what exactly the rotate is doing if you do not know deques.

2

u/__Abigail__ Dec 09 '18

Very similar to my Perl solution. Although in Perl, I just arrays, as in Perl it's very easy to add/remove things from the end/beginning of the array.

3

u/robertlagrant Dec 09 '18

Mine was scarily almost identical to yours.

from aoc2018.inputs import day9input

from collections import deque, defaultdict
from itertools import cycle


def run_game(_max_marble, _player_count):
    elves = defaultdict(int)
    circle = deque()

    for current_marble, current_elf in zip(range(_max_marble+1), cycle(range(_player_count))):
        if current_marble and current_marble % 23 == 0:
            circle.rotate(7)
            elves[current_elf] += current_marble + circle.pop()
            circle.rotate(-1)
        else:
            circle.rotate(-1)
            circle.append(current_marble)

    return max(elves.values())


player_count, max_marble = map(int, (day9input.parsed["player_count"], day9input.parsed["max_value"]))

print(f"Part 1: {run_game(max_marble, player_count)}")
print(f"Part 2: {run_game(max_marble*100, player_count)}")
→ More replies (2)

3

u/EdeMeijer Dec 09 '18

I have the same thing in Rust, with the small difference that Rust's linked list doesn't have this nice rotate functionality. So I did what everyone would do, and implement my own custom circular list :)

https://github.com/EdeMeijer/aoc2018/blob/master/src/days/day9.rs

My identical solve function:

fn solve(players: usize, max_marble: usize) -> usize {
    let mut scores = vec![0usize; players];

    let mut circle = CircularList::with_capacity(max_marble + 1);
    circle.insert(0usize);

    for marble in 1..=max_marble {
        if marble % 23 == 0 {
            scores[marble % players] += circle.seek(-7).remove().unwrap() + marble;
        } else {
            circle.next().insert(marble);
        }
    }

    scores.into_iter().max().unwrap()
}

2

u/Grzi_ Dec 09 '18 edited Dec 09 '18

Glad to see some Rust

Take a look at this, I thing I did a pretty good one for this day (In Rust)

use std::collections::VecDeque;

fn calculate_high_score(_player_nb: usize, _marble_number: usize ) -> usize{
    let mut players_score = vec!(0; _player_nb);
    let mut ring = VecDeque::new();
    ring.push_front(0);

    for marble in 1.._marble_number {
        if marble % 23 == 0{
            // rotate of 7 behind + delete
            (0..7).for_each(|_| { 
                let tmp = ring.pop_back().expect("Rotate problem"); 
                ring.push_front(tmp); 
            } );
            players_score[marble % _player_nb] += 
                    marble + ring.pop_front().expect("No value in the ring");
        }else{
            // rotate of 2 ahead + insert
            (0..2).for_each(|_| { 
                let tmp = ring.pop_front().expect("Rotate problem");        
                ring.push_back(tmp);
            });
            ring.push_front(marble);
        }
    }
    *players_score.iter().max().expect("No value in the player scores")
}
→ More replies (2)

1

u/FogLander Dec 09 '18 edited Dec 09 '18

Are you just keeping track of current_marble_index for clarity? this code:

circle.rotate(8)
scores[player] += marble + circle.pop()
circle.rotate(-2)

would work the same from what I can tell, although it has the disadvantage of being somewhat less clear.

Edit: ok, his code above has now been edited so my comment is no longer relevant

2

u/Clipsterman Dec 09 '18

Not the poster, but unless I am totally misremembering, pop removes the last element, so they wouldn't be equivalent.

→ More replies (1)

1

u/sbjf Dec 09 '18

Aw fuck, I completely forgot about deque and proceeded to implement my own linked list in python.

1

u/phlummox Dec 24 '18

I was hoping there was a clever trick to be found that I hadn't spotted. But it seems like (so far) using a linked list is as good as it gets.