Guest User

day3

a guest
Dec 3rd, 2021
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.68 KB | None | 0 0
  1. <?php
  2.  
  3. $input = file('input.txt');
  4. //$input = file('example.txt');
  5.  
  6. $nbBits = strlen($input[0])  - 2;
  7. $nbLines = count($input);
  8.  
  9. $gamma = [];
  10. $epsilon = [];
  11. $sum = [];
  12.  
  13. for($pos=0; $pos < $nbBits; $pos++){
  14.     $sum[$pos] = 0;
  15.     foreach($input as $line){
  16.         $val = (int) substr($line, $pos, 1);
  17.         $sum[$pos] += $val;
  18.         if($sum[$pos] > ($nbLines/2)){
  19.             $gamma[$pos] = 1;
  20.             $epsilon[$pos] = 0;
  21.             //continue 2;
  22.         }
  23.     }
  24.     if(!array_key_exists($pos, $gamma)) {
  25.         $gamma[$pos] = 0;
  26.         $epsilon[$pos] = 1;
  27.     }
  28. }
  29.  
  30. $strGamma = implode($gamma);
  31.  
  32. $decGamma = bindec($strGamma);
  33. echo $strGamma, ' => ', $decGamma, PHP_EOL;
  34.  
  35. $strEpsilon = implode($epsilon);
  36. $decEspilon = bindec($strEpsilon);
  37. echo $strEpsilon, ' => ', $decEspilon,PHP_EOL;
  38.  
  39. echo 'part1  : ', $decGamma * $decEspilon, PHP_EOL,PHP_EOL;
  40.  
  41. //part 2
  42. function matching(array $candidates, array $sums, $type, $pos = 0) : array
  43. {
  44.     if(count($candidates) == 1)
  45.         return $candidates;
  46.  
  47.     if($sums[$pos] >= (count($candidates)/2) )
  48.         $valid = $type;
  49.     else
  50.         $valid = abs($type - 1);
  51.  
  52.     foreach ($candidates as $i=>$candidate){
  53.         $val = (int)substr($candidate, $pos, 1);
  54.         if($val !== $valid) {
  55.             unset($candidates[$i]);
  56.             for($j = $pos + 1; $j < count($sums); $j++){
  57.                 $sums[$j] -= (int)substr($candidate, $j, 1);
  58.             }
  59.         }
  60.     }
  61.     return matching($candidates, $sums, $type,$pos+1);
  62. }
  63.  
  64. $oxygen = matching($input, $sum, 1);
  65. $scrubber = matching($input, $sum, 0);
  66.  
  67. echo 'part2  : ', bindec(array_pop($oxygen)) * bindec(array_pop($scrubber)), PHP_EOL,PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment