copy pasting the rules from last year’s thread:

Rules: no spoilers.

The other rules are made up aswe go along.

Share code by link to a forge, home page, pastebin (Eric Wastl has one here) or code section in a comment.

  • Mii@awful.systems
    link
    fedilink
    English
    arrow-up
    1
    ·
    14 days ago
    Day 2, Part 1
    use strict;
    use List::Util qw( min max );
    
    open(FH, '<', $ARGV[0]) or die $!;
    my @lines;
    while (<FH>) {
    	my @report = split /\s/, $_;
    	push @lines, \@report;
    }
    
    close FH;
    
    sub in_range {
    	my $diff = max($_[0], $_[1]) - min($_[0], $_[1]);
    	return $diff >= 1 && $diff <= 3;
    }
    
    sub is_safe {
    	my $prev = @$_[0];
    	my $dir = 0;
    
    	for (my $i = 1; $i < scalar @$_; ++$i) {
    		my $el = @$_[$i];
    		if ($el > $prev) {
    			return 0 unless $dir >= 0;
    			$dir = 1;
    		} elsif ($el < $prev) {
    			return 0 unless $dir <= 0;
    			$dir = -1;
    		}
    
    		return 0 unless in_range $prev, $el;
    		$prev = $el;
    	}
    
    	return 1;
    }
    
    sub part1 {
    	my $safe_reports = 0;
    
    	foreach (@_) {
    		$safe_reports++ if is_safe @$_;
    	}
    
    	return $safe_reports;
    }
    
    print 'Part 1: ', part1(@lines), "\n";
    

    My part 2 solution didn’t work with the real input but worked with all the test cases I threw at it, so I couldn’t figure out what was wrong with it and I’m too lazy to debug any more right now.