Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use List::AllUtils qw(notall indexes product);
- use Curses;
- use Time::HiRes qw(sleep);
- my $DELAY = 0.1;
- my $cur = new Curses;
- Curses::initscr();
- $cur->clear();
- $/ = '';
- my @valid;
- my @f_valid;
- # Read ranges:
- $_ = <>;
- my @field_names;
- my $f_num = 0;
- foreach (split( "\n" )) {
- m#(.*):#g;
- push( @field_names, ucfirst $1 );
- foreach my $range (map { s#-#..#r } (m#\d+-\d+#g)) {
- foreach (eval( $range )) {
- $valid[ $_ ] = 1;
- $f_valid[ $f_num ][ $_ ] = 1;
- }
- }
- $f_num++;
- }
- $f_num--;
- # Read my ticket:
- $_ = <>;
- my @mine = m#\d+#g;
- foreach my $i (0 .. $f_num) {
- $cur->addstr( $i + 1, 5, sprintf( "%s %3d", ',' x ($f_num + 1), $mine[$i] ) );
- }
- $cur->refresh();
- # Read nearby tickets:
- $_ = <>;
- my @f_table;
- foreach my $i (0 .. $f_num) {
- %{$f_table[$i]} = map { $_ => 1 } (0 .. $f_num); # init table to all valid
- }
- foreach (split( "\n" )) {
- my @ticket = m#\d+#g;
- next if (!@ticket || notall { $valid[$_] } @ticket); # toss out invalid ones
- # scan to remove invalid possibilities from table:
- foreach my $i (0 .. $f_num) {
- foreach my $f (0 .. $f_num) {
- if (!$f_valid[$f][ $ticket[$i] ]) {
- delete $f_table[$i]{$f};
- $cur->addch( $i + 1, 5 + $f, 'X' );
- $cur->refresh();
- sleep( $DELAY / 10 );
- }
- }
- }
- }
- # Find the ones with only one choice, mark them in the key, delete for others, repeat
- #printf "\nSolving:\n";
- my @answer_key;
- foreach (0 .. $f_num) {
- foreach my $i (indexes { keys %$_ == 1 } @f_table) {
- my $ans = (keys %{$f_table[$i]})[0];
- $answer_key[$ans] = $i;
- $cur->addch( $i + 1, 5 + $ans, 'O' );
- $cur->refresh();
- sleep( $DELAY );
- foreach (0 .. $f_num) {
- delete $f_table[$_]{$ans};
- $cur->addch( $_ + 1, 5 + $ans, '.' ) if ($_ != $i);
- }
- $cur->addstr( $i + 1, $f_num + 13 , $field_names[ $ans ] );
- $cur->refresh();
- sleep( $DELAY );
- }
- }
- #
- # Hardcoding in fields 0-5, because these are the "departure" ones in my input
- $cur->addstr( 3 + $f_num, 5, sprintf( "Part 2: %d", product( map { $mine[ $answer_key[$_] ] } (0 .. 5) )));
- $cur->refresh();
- Curses::endwin();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement