-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day15Part2.ps1
49 lines (42 loc) · 942 Bytes
/
Day15Part2.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function ElfHash {
param (
$String
)
$Hash = 0
for ($ndx = 0; $ndx -lt $String.Length; $ndx++) {
$Hash += [byte][char]$String.SubString($ndx, 1)
$Hash *= 17
$Hash = $Hash % 256
}
$Hash
}
$Sequence = (Get-Clipboard) -split "," | ?{$_ -ne ""}
$Boxes = @{}
$Sum = 0
foreach ($Step in $Sequence) {
if ($Step -match '(\w*)(=|-)(\d*)') {
$Label = $Matches[1]
$Operation = $Matches[2]
$Value = $Matches[3]
} else {
"Bad"
}
$Box = ElfHash $Label
if (-not $Boxes.ContainsKey($Box)) {
$Boxes[$Box] = [ordered]@{}
}
if ($Operation -eq "=") {
$Boxes[$Box][$Label] = $Value
} else {
$Boxes[$Box].Remove($Label)
}
}
$Sum = 0
foreach ($Box in $Boxes.Keys) {
$ndx = 0
foreach ($Value in $Boxes[$Box].Keys) {
$ndx++
$Sum += ($Box + 1) * $ndx * $Boxes[$Box][$Value]
}
}
$Sum