Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $filename = "11.txt";
- open(FILE, $filename);
- @data = <FILE>;
- close(FILE);
- #Read in input as 2d array
- for ($a = 0; $a < 10; $a++) {
- $line = $data[$a];
- $line =~ s/[^0-9]*//sgi;
- @toprow = split("", $line);
- for ($b = 0; $b < 10; $b++) {
- $octo[$a][$b] = int($toprow[$b]);
- }
- }
- $flashcount = 0;
- for ($round = 0; $round < 1000000; $round++) { #Yeah 1 million is overkill, but the loop will surely exit when it found a step where all octopuses flashed.
- #Do +1 to all cells
- for ($b = 0; $b < 10; $b++) {
- for ($a = 0; $a < 10; $a++) {
- $octo[$a][$b]++;
- }
- }
- #While loop until no more changes to board can be made
- $changed = 1;
- while ($changed == 1) {
- $changed = 0;
- for ($b = 0; $b < 10; $b++) {
- for ($a = 0; $a < 10; $a++) {
- if ($octo[$a][$b] > 9) { #Cell that need to flash
- $changed = 1;
- $octo[$a][$b] = -1; #Flash cell **AND** "lockout" cell so it cannot receive energy more.
- $flashcount++;
- if ($a > 0) { #Boundary checks - if the cells are adjacent to the wall we shouldn't start flashing non-existent octopuses
- if ($b < 9) {
- if ($octo[$a - 1][$b + 1] > -1) { #Make sure cell isn't locked before receiving energy.
- $octo[$a - 1][$b + 1]++;
- }
- }
- if ($b > 0) {
- if ($octo[$a - 1][$b - 1] > -1) {
- $octo[$a - 1][$b - 1]++;
- }
- }
- if ($octo[$a - 1][$b] > -1) {
- $octo[$a - 1][$b]++;
- }
- }
- if ($a < 9) {
- if ($b < 9) {
- if ($octo[$a + 1][$b + 1] > -1) {
- $octo[$a + 1][$b + 1]++;
- }
- }
- if ($b > 0) {
- if ($octo[$a + 1][$b - 1] > -1) {
- $octo[$a + 1][$b - 1]++;
- }
- }
- if ($octo[$a + 1][$b] > -1) {
- $octo[$a + 1][$b]++;
- }
- }
- if ($b < 9) {
- if ($octo[$a][$b + 1] > -1) {
- $octo[$a][$b + 1]++;
- }
- }
- if ($b > 0) {
- if ($octo[$a][$b - 1] > -1) {
- $octo[$a][$b - 1]++;
- }
- }
- }
- }
- }
- }
- $indiflash = 0;
- for ($b = 0; $b < 10; $b++) {
- for ($a = 0; $a < 10; $a++) {
- if ($octo[$b][$a] == -1) { #Check for locked cells
- $octo[$b][$a] = 0; #Unlock cells
- $indiflash++; #Count flashes during a step
- }
- }
- }
- if ($indiflash == 100) { #All octopuses flashed at once
- last; #Found answer to part2
- }
- if ($round == 99) {
- $lastflashcount = $flashcount; #Found answer to part 1
- }
- }
- print $lastflashcount."\n";
- $round++; # $round starts from 0, while step in question starts from 1.
- print $round."\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement