Quick actions

cmd+k|ctrl+k

Navigation

Languages

AoC 2022, day 9

Snippet info

Language

Raku

Visibility

public

Author

seaker

Created

2022-12-09T06:14:46.036054Z

Updated

2022-12-09T06:20:03.991286Z

sub is-touching(@H, @T --> Bool:D) {
    so (@H[0] - @T[0]) & (@H[1] - @T[1]) == -1|0|1
}                              
                                                                               
sub simulate(@movements, UInt:D \knot-num--> UInt:D) {
    my @knots = [0, 0] xx knot-num;
    my %trail is SetHash;
 
    for @movements -> \drt, \dst {
        for 1 .. dst.Int {
            given drt {
                when 'U' { ++@knots[0;1] }
                when 'D' { --@knots[0;1] }
                when 'L' { --@knots[0;0] }
                when 'R' { ++@knots[0;0] }
            }

            for 1 ..^ knot-num -> \k {
                unless is-touching(@knots[k-1], @knots[k]) {
                    @knots[k;0] += (@knots[k-1;0] - @knots[k;0]).sign;
                    @knots[k;1] += (@knots[k-1;1] - @knots[k;1]).sign;
                }
            }

            %trail.set("{ @knots[knot-num - 1; 0] }:{ @knots[knot-num - 1;1] }");
        }
    }

    +%trail
}

with $*IN.words -> @movements {
    put 'part 1: ', simulate(@movements, 2);
    put 'part 2: ', simulate(@movements, 10);
}
INFO