Guest User

Untitled

a guest
Dec 12th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.16 KB | None | 0 0
  1. <?php
  2. $input = file('input.txt');
  3.  
  4. $initial_state = str_replace("\n",'',str_replace('initial state: ','',array_shift($input)));
  5. $charmaps = array();
  6.  
  7. for($i=1;$i<count($input);$i++)
  8. {
  9.     list($key, $value) = explode(' => ', $input[$i]);
  10.     $charmaps[$key] = $value[0];
  11. }
  12.  
  13. function get_generation($generation, $initial_state, $charmaps, $search_diff = false)
  14. {
  15.     $padding = $generation*2;
  16.  
  17.     $padding_string = implode('',array_fill(0,$padding,'.'));
  18.  
  19.     $search_string = $padding_string . $initial_state . $padding_string;
  20.  
  21.     $generations = $generation;
  22.     $last_sum = 0;
  23.     $diff = 0;
  24.     $trend = array();
  25.  
  26.     for($i=0;$i<$generations;$i++)
  27.     {
  28.         $new_generation = substr($search_string,0,2);
  29.  
  30.         for($j=2;$j<strlen($search_string);$j++)
  31.         {
  32.             $searchkey = substr($search_string,$j-2,5);
  33.             if(isset($charmaps[$searchkey]))
  34.             {
  35.                 $new_generation .= $charmaps[$searchkey];
  36.             } else {
  37.                 $new_generation .= '.';//$search_string[$j];
  38.             }
  39.         }
  40.         $search_string = $new_generation;
  41.  
  42.         $sum =0;
  43.  
  44.         for($x=0;$x<strlen($search_string);$x++)
  45.         {
  46.             if($search_string[$x] == '#')
  47.             {
  48.                 $sum += $x - $padding;
  49.             }
  50.         }
  51.  
  52.         $diff = $sum - $last_sum;
  53.  
  54.         $last_sum = $sum;
  55.  
  56.         if($search_diff)
  57.         {
  58.             $trend[] = $diff;
  59.             $vals = array_count_values($trend);
  60.  
  61.             //assume we have a trend when the diff is the most common diff count > 8
  62.             $check_diff = array_search(8, $vals);
  63.             if($check_diff && $check_diff == $diff) {
  64.                 return array('sum' => $sum, 'diff' => $check_diff, 'gen' => $i+1);
  65.             }
  66.         }
  67.  
  68.     }
  69.  
  70.  
  71.     return array('sum'=>$sum, 'diff'=>$diff, 'gen'=>$i);
  72. }
  73.  
  74. printf('Part 1: %d', get_generation(20, $initial_state, $charmaps)['sum']);
  75. echo PHP_EOL;
  76.  
  77. $gen_search = 500;
  78.  
  79. $result = get_generation($gen_search, $initial_state, $charmaps, true);
  80. $sum = $result['sum'] + $result['diff'] * (50000000000 -  $result['gen']);
  81. printf('Part 2: %d', $sum);
  82. echo PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment