Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #https://adventofcode.com/2021/day/3
- #Part 2 using Regex
- #Select first bit of the previous answer to create the regex
- $oxygen_regex = "^$($gamma[0])"
- $co2_regex = "^$($epsilon[0])"
- #Empty variable to store the answers
- $oxygen_binary = ""
- $co2_binary = ""
- #Looping from second to last bit of each input as we already have the first one from previous part
- 1..11 | % {
- $bit = $_
- #custom object acting like a meter for both oxygen and co2
- $bit_count = [pscustomobject]@{"0"=0;"1"=0 ;"2"=0;"3"=0}
- #if only 1 match left, select it as the answer
- if(($binary -match $oxygen_regex).Count -eq 1){
- $oxygen_binary = $binary -match $oxygen_regex
- }
- else{
- #Select each element from the puzzle input matching the regex
- $binary -match $oxygen_regex | % {
- if ($_[$bit] -eq "1"){
- $bit_count.1 += 1
- }
- else{
- $bit_count.0 += 1
- }
- }
- #Append the regex deppending on the most common bit for the current index
- if ($bit_count.0 -gt $bit_count.1){
- $oxygen_regex += "0"
- }
- else{
- $oxygen_regex += "1"
- }
- }
- #Same part/logic applied, but reverted for co2
- if(($binary -match $co2_regex).Count -eq 1){
- $co2_binary = $binary -match $co2_regex
- }
- else{
- $binary -match $co2_regex | % {
- if ($_[$bit] -eq "1"){
- $bit_count.3 += 1
- }
- else{
- $bit_count.2 += 1
- }
- }
- if ($bit_count.3 -lt $bit_count.2){
- $co2_regex += "1"
- }
- else{
- $co2_regex += "0"
- }
- }
- }
- $part_2_result = ([convert]::ToInt32($co2_binary,2)) * ([convert]::ToInt32($oxygen_binary,2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement