Advertisement
Acquira

Advent of Code 2021 Day 3 Part 2

Dec 8th, 2021
1,248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #https://adventofcode.com/2021/day/3
  2.  #Part 2 using Regex
  3.  
  4. #Select first bit of the previous answer to create the regex
  5. $oxygen_regex = "^$($gamma[0])"
  6. $co2_regex = "^$($epsilon[0])"
  7.  
  8. #Empty variable to store the answers
  9. $oxygen_binary = ""
  10. $co2_binary = ""
  11.  
  12. #Looping from second to last bit of each input as we already have the first one from previous part
  13. 1..11 | % {
  14.     $bit = $_
  15.  
  16.     #custom object acting like a meter for both oxygen and co2
  17.     $bit_count = [pscustomobject]@{"0"=0;"1"=0 ;"2"=0;"3"=0}
  18.  
  19.     #if only 1 match left, select it as the answer
  20.     if(($binary -match $oxygen_regex).Count   -eq 1){
  21.         $oxygen_binary = $binary -match $oxygen_regex
  22.     }
  23.     else{
  24.         #Select each element from the puzzle input matching the regex
  25.         $binary -match $oxygen_regex | % {
  26.             if ($_[$bit] -eq "1"){
  27.                 $bit_count.1 += 1
  28.             }
  29.             else{
  30.                 $bit_count.0 += 1
  31.             }
  32.         }
  33.         #Append the regex deppending on the most common bit for the current index
  34.         if ($bit_count.0 -gt $bit_count.1){
  35.             $oxygen_regex += "0"
  36.         }
  37.         else{
  38.             $oxygen_regex += "1"
  39.         }
  40.     }
  41.    
  42.     #Same part/logic applied, but reverted for co2
  43.     if(($binary -match $co2_regex).Count   -eq 1){
  44.         $co2_binary = $binary -match $co2_regex        
  45.     }
  46.     else{
  47.         $binary -match $co2_regex | % {
  48.             if ($_[$bit] -eq "1"){
  49.                 $bit_count.3 += 1
  50.             }
  51.             else{
  52.                 $bit_count.2 += 1
  53.             }
  54.         }
  55.         if ($bit_count.3 -lt $bit_count.2){
  56.             $co2_regex += "1"
  57.         }
  58.         else{
  59.             $co2_regex += "0"
  60.         }
  61.     }
  62.  
  63. }
  64.  
  65. $part_2_result = ([convert]::ToInt32($co2_binary,2)) * ([convert]::ToInt32($oxygen_binary,2))
  66.  
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement