Day 11: Cosmic Expansion

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


🔒 Thread is locked until there’s at least 100 2 star entries on the global leaderboard

🔓 Unlocked after 9 mins

  • vole@lemmy.world
    link
    fedilink
    English
    arrow-up
    3
    ·
    edit-2
    1 year ago

    Raku

    Today I’m thankful that I have the combinations() method available. It’s not hard to implement combinations(), but it’s not particularly interesting. This code is a bit anachronistic because I solved part 1 by expanding the universe instead of contracting it, but this way makes the calculations for part 1 and part 2 symmetric. I was worried for a bit there that I’d have to do some “here are all the places where expansion happens, check this list when calculating distances” bookkeeping, and I was quite relieved when I realized that I could just use arithmetic.

    edit: Also, first time using the Slip class in Raku, which is mind bending, but very useful for expanding/contracting the universe and generating the lists of galaxy coordinates. And I learned a neat way to transpose 2D arrays using [Z].

    View the code on Github

    Code
    use v6;
    
    sub MAIN($input) {
        my $file = open $input;
    
        my @map = $file.lines».comb».Array;
        my @galaxies-original = @map».grep("#", :k).grep(*.elems > 0, :kv).rotor(2).map({($_[0] X $_[1]).Slip});
        my $distances-original = @galaxies-original.List.combinations(2).map({($_[0] Z- $_[1])».abs.sum}).sum;
    
        # contract the universe
        @map = @map.map: {$_.all eq '.' ?? slip() !! $_};
        @map = [Z] @map;
        @map = @map.map: {$_.all eq '.' ?? slip() !! $_};
        @map = [Z] @map;
    
        my @galaxies = @map».grep("#", :k).grep(*.elems > 0, :kv).rotor(2).map({($_[0] X $_[1]).Slip});
        my $distances-contracted = @galaxies.List.combinations(2).map({($_[0] Z- $_[1])».abs.sum}).sum;
    
        my $distances-twice-expanded = ($distances-original - $distances-contracted) * 2 + $distances-contracted;
        say "part 1: $distances-twice-expanded";
        my $distances-many-expanded = ($distances-original - $distances-contracted) * 1000000 + $distances-contracted;
        say "part 2: $distances-many-expanded";
    }