Advertisement
musifter

AoC day 11, Curses pt2

Dec 11th, 2020 (edited)
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use Curses;
  7. use Time::HiRes qw(sleep);
  8.  
  9. my $DELAY = 0.5;
  10.  
  11. # Init curses - draw initial display
  12. my $cur = new Curses;
  13.  
  14. Curses::initscr();
  15. $cur->clear();
  16.  
  17. my @DIRS = ([-1,-1], [-1,0], [-1,1], [ 0,-1], [ 0,1], [ 1,-1], [ 1,0], [ 1,1]);
  18.  
  19. # Read Grid into buffer adding spaces for quick and easy boundary handling
  20. # Grid[ buffer ][ ycoord ][ xcoord ]
  21. my @Grid = [map { chomp; [' ', split(//), ' '] } <>];
  22. my $X_SIZE = @{$Grid[0][0]};
  23.  
  24. # borders for the top and bottom
  25. unshift( @{$Grid[0]}, [(' ') x $X_SIZE] );
  26. push( @{$Grid[0]}, [(' ') x $X_SIZE] );
  27. my $Y_SIZE = @{$Grid[0]};
  28.  
  29. # initialize other buffer
  30. $Grid[1] = [ map { [(' ') x $X_SIZE] } (0 .. $Y_SIZE) ];
  31.  
  32.  
  33. $cur->addstr( 0, 0, "Generation: 0 Occupied: 0 Changes: 0" );
  34. for (my $y = 1; $y < $Y_SIZE - 1; $y++) {
  35. for (my $x = 1; $x < $X_SIZE - 1; $x++) {
  36. $cur->addch( $y, $x - 1, $Grid[0][$y][$x] );
  37. }
  38. }
  39. $cur->refresh();
  40.  
  41. # for swapping between old and new buffers
  42. my ($old, $new) = (0, 1);
  43.  
  44. # Return count of adjacent occupied squares
  45. sub get_occupied {
  46. my ($y, $x) = @_;
  47.  
  48. my $ret = 0;
  49. foreach my $d (@DIRS) {
  50. my ($ny, $nx) = ($y + $d->[0], $x + $d->[1]);
  51. while ($Grid[$old][$ny][$nx] eq '.') {
  52. ($ny, $nx) = ($ny + $d->[0], $nx + $d->[1]);
  53. }
  54.  
  55. $ret += ($Grid[$old][$ny][$nx] eq '#');
  56. }
  57.  
  58. return ($ret);
  59. }
  60.  
  61.  
  62. my ($gen, $changes, $total_occ) = (0,1,0);
  63. while ($changes) {
  64. ($changes, $total_occ) = (0,0);
  65. for (my $y = 1; $y < $Y_SIZE - 1; $y++) {
  66. for (my $x = 1; $x < $X_SIZE - 1; $x++) {
  67. my $occ = &get_occupied( $y, $x );
  68.  
  69. if ($Grid[$old][$y][$x] eq 'L' && $occ == 0) {
  70. $Grid[$new][$y][$x] = '#';
  71. $cur->addch( $y, $x - 1, '#' );
  72. $changes++;
  73. } elsif ($Grid[$old][$y][$x] eq '#' && $occ >= 5) {
  74. $Grid[$new][$y][$x] = 'L';
  75. $cur->addch( $y, $x - 1, 'L' );
  76. $changes++;
  77. } else {
  78. $Grid[$new][$y][$x] = $Grid[$old][$y][$x];
  79. }
  80.  
  81. $total_occ += ($Grid[$new][$y][$x] eq '#');
  82. }
  83. }
  84.  
  85. $cur->addstr( 0, 0, sprintf( "Generation: %4d Occupied: %4d Changes: %4d\r", ++$gen, $total_occ, $changes ) );
  86. $cur->refresh();
  87. sleep( $DELAY );
  88.  
  89. ($old, $new) = ($new, $old);
  90. }
  91.  
  92. Curses::endwin();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement