Guest User

Untitled

a guest
Dec 1st, 2024
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 1.01 KB | Source Code | 0 0
  1. # Advent of Code 2024 Day 1 in PowerShell
  2. # Faster code.
  3. # Edit the path to the input text file
  4. # save as faster.ps1
  5. # run from powershell
  6.  
  7. measure-command {
  8.  
  9. $Col1 = [system.collections.generic.list[int]]::new()
  10. $Col2 = [system.collections.generic.list[int]]::new()
  11.  
  12. # load data
  13. $FileLines = [system.io.file]::ReadAllLines('C:\path\to\day1-input.txt')
  14.  
  15. foreach ($line in $FileLines) {
  16.     $num1, $num2 = $line.Split(' ', [System.StringSplitOptions]::RemoveEmptyEntries)
  17.     $null = $Col1.Add($num1)
  18.     $null = $Col2.Add($num2)
  19. }
  20.  
  21. $Col1.Sort()
  22. $Col2.Sort()
  23.  
  24.  
  25. # part 1
  26. $Part1Sum = 0
  27. for ($i=0; $i -lt $Col1.Count; $i++) {
  28.     $Part1Sum += [math]::Abs($Col1[$i] - $Col2[$i])
  29. }
  30.  
  31.  
  32. # part 2
  33. $counter = [system.collections.generic.dictionary[int, int]]::new()
  34. foreach ($num2 in $Col2) {
  35.     $counter[$num2]++
  36. }
  37.  
  38. $Part2Sum = 0
  39. foreach ($num2 in $Col1) {
  40.     $Part2Sum+= $num2 * $counter[$num2]
  41. }
  42.  
  43. } | foreach { "$($_.Milliseconds) milliseconds" }
  44.  
  45. "Part 1: $Part1Sum"
  46. "Part 2: $Part2Sum"
  47.  
Tags: powershell
Advertisement
Add Comment
Please, Sign In to add comment