-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday9.ps1
69 lines (40 loc) · 1.45 KB
/
day9.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Day 9
# https://adventofcode.com/2024/day/9
# Part 1
# Use a queue to store each fileid and free space
# Convert that to an ArrayList
# Find each first free space and take the fileid from the end and move it.
#$data = "2333133121414131402"
$data = Get-Content .\day9_input.ps1
#append 0 to last position to reduce check at end
$data += "0"
$disk = new-object System.Collections.Queue
$fileid = 0
for($block = 0 ; $block -lt $data.Length ; $block+=2) {
$used = [int32][char]::GetNumericValue($data[$block])
#write-host $used
for ($i = 0; $i -lt $used; $i++) {$disk.Enqueue($fileid) }
$space = [int32][char]::GetNumericValue($data[$block+1])
for ($j = 0; $j -lt $space; $j++) {$disk.Enqueue(".") }
$fileid+=1
}
$array = $disk.ToArray()
$arrayList = New-Object System.Collections.ArrayList
foreach ($element in $array) {
[void]$arrayList.Add($element)
}
# fill in spaces at beginning with elements from the ends
$firstfree = $arraylist.IndexOf(".")
for ($j = ($arraylist.Count-1) ; $j -gt $firstfree; $j--) {
$firstfree = $arraylist.IndexOf(".")
if ($arraylist[$j] -ne "." -and $j -gt $firstfree) {$arraylist[$firstfree] = $arraylist[$j]; $arraylist[$j] ="."}
#$arraylist -join ""
}
$sum = 0
for ($j=0; $j -lt $arraylist.count; $j++) {
if ($arraylist[$j] -ne "." ) {$product = $arraylist[$j] * $j; $sum += $product}
#$arraylist -join ""
}
write-host "Checksum: $sum"
# ans 1: 24914453918645 too high
# ans 2: 6446899523367