Acquira

Advent of Code 2021 Day 3 Part 1

Dec 8th, 2021 (edited)
953
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #https://adventofcode.com/2021/day/3
  2.  
  3. # WebRequest to gather your puzzle input
  4. $cookie_id = "53616xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  5. $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
  6. $session.Cookies.Add((New-Object System.Net.Cookie("session", $cookie_id, "/", ".adventofcode.com")))
  7. $binary = Invoke-WebRequest -UseBasicParsing -Uri "https://adventofcode.com/2021/day/3/input" ` -WebSession $session
  8. $binary = $binary.Content
  9.  
  10. # Format the input content as an array by splitting it line by line
  11. $binary = $binary -split("\n")
  12.  
  13. #Create a custom object to compare each bit "0" or "1"
  14. $counting_array = @()
  15. 0..($binary[0].Length -1) | % {
  16.     $counting_array += [pscustomobject]@{
  17.         "0"= 0
  18.         "1"= 0
  19.     }
  20. }
  21.  
  22. #Parse over the puzzle input and count if bits are 0 or 1
  23. $binary | % {
  24.     $bin = $_
  25.     0..($bin.length - 1)|% {
  26.         if ($bin[$_] -eq "0"){
  27.             $counting_array[$_].0 += 1
  28.         }
  29.         else{
  30.             $counting_array[$_].1 += 1
  31.         }
  32.     }
  33. }
  34.  
  35. #Store the binary as strings
  36. [string]$gamma   = ""
  37. [string]$epsilon = ""
  38.  
  39. #Compare for each bit if there are more 0 or 1 and append it to the binary strings
  40. $counting_array | % {
  41.     if($_.0 -gt $_.1){
  42.         $gamma+="0"
  43.         $epsilon+="1"
  44.     }
  45.     else{
  46.         $gamma+="1"
  47.         $epsilon+="0"
  48.     }
  49. }
  50.  
  51. #Convert the strings to INT32 and multiply them to get the first part answer
  52. $part_1_answer = ([convert]::ToInt32($gamma,2))*([convert]::ToInt32($epsilon,2))
  53.  
RAW Paste Data