crlogic

Day5

Dec 5th, 2022
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. # Part 1
  2. [string[]]$bothInstructions = $puzzleInput -split '\n' | Select -SkipLast 1
  3. $startingPosition = $bothInstructions[0..7]
  4. $moveInstructions = $bothInstructions[10..$bothInstructions.count]
  5.  
  6. # Populate stacks
  7. $stackCollection = @{}
  8. $columnidx = 1
  9. 1..9 | foreach {
  10. [int]$stack = $_
  11. $stackCollection.$stack = [System.Collections.Generic.List[char]]::new()
  12. Write-Verbose "Working stack $stack" -Verbose
  13. 0..7 | foreach {
  14. [int]$row = $_
  15. if (-not [string]::IsNullOrWhiteSpace($startingPosition[$row][$columnidx])) {
  16. ($stackCollection.$stack).Add($startingPosition[$row][$columnidx])
  17. }
  18. }
  19. $columnidx += 4
  20. ($stackCollection.$stack).Reverse()
  21. }
  22.  
  23. # Do moves
  24. foreach ($moveStr in $moveInstructions) {
  25. [int]$move,[int]$from,[int]$to = $moveStr -split 'move|from|to|\s' | Where {-not [string]::IsNullOrWhiteSpace($_)}
  26. 1..$move | Foreach {
  27. [char]$moveItem = ($stackCollection.$from)[-1]
  28. ($stackCollection.$from).RemoveAt($stackCollection.$from.count-1)
  29. ($stackCollection.$to).Add($moveItem)
  30. }
  31. }
  32. (1..9 | foreach {($stackCollection.$_)[-1]}) -join ''
  33.  
  34. # Part 2
  35. # using clean $stackCollection
  36. foreach ($moveStr in $moveInstructions) {
  37. [int]$move,[int]$from,[int]$to = $moveStr -split 'move|from|to|\s' | Where {-not [string]::IsNullOrWhiteSpace($_)}
  38. if ($move -gt 1) {
  39. [char[]]$moveItems = $null
  40. 1..$move | Foreach {
  41. [char]$moveItem = ($stackCollection.$from)[-1]
  42. ($stackCollection.$from).RemoveAt($stackCollection.$from.count-1)
  43. [char[]]$moveItems += $moveItem
  44. }
  45. [array]::Reverse($moveItems)
  46. $moveItems | Foreach {($stackCollection.$to).Add($_)}
  47. }
  48. else {
  49. [char]$moveItem = ($stackCollection.$from)[-1]
  50. ($stackCollection.$from).RemoveAt($stackCollection.$from.count-1)
  51. ($stackCollection.$to).Add($moveItem)
  52. }
  53. }
  54. (1..9 | foreach {($stackCollection.$_)[-1]}) -join ''
Advertisement
Add Comment
Please, Sign In to add comment