Skip to content

Commit

Permalink
day 09
Browse files Browse the repository at this point in the history
  • Loading branch information
Le0Developer committed Dec 9, 2024
1 parent 7c4c87b commit 5a91ed4
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 0 deletions.
Empty file removed 2024/09/.gitkeep
Empty file.
1 change: 1 addition & 0 deletions 2024/09/diskmap.input
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
2333133121414131402
111 changes: 111 additions & 0 deletions 2024/09/leodev.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import os

fn main() {
line := os.read_file('diskmap.input')!

mut layout := []int{}
for i := 0; i < line.len; i += 2 {
file_len := line[i] - `0`
for _ in 0 .. file_len {
layout << (i >> 1)
}

if i + 1 >= line.len {
break
}
gap_len := line[i + 1] - `0`
for _ in 0 .. gap_len {
layout << -1
}
}

print_layout(layout)

mut l := 0
mut r := layout.len - 1
mut fragment := layout.clone()
for {
for fragment[l] != -1 {
l++
}
for fragment[r] == -1 {
r--
}
if l >= r {
break
}
fragment[l] = fragment[r]
fragment[r] = -1
}

print_layout(fragment)

println('part1: ${checksum(fragment)}')

mut compact := layout.clone()
r = compact.len - 1
outer: for {
for r > 0 && compact[r] == -1 {
r--
}
l = r
file_type := compact[r] or { panic('impossible') }
for l > 0 && compact[l - 1] == file_type {
l--
}
if l == 0 {
break
}
file_len := r - l + 1

mut fl := 0
for {
for fl < compact.len && compact[fl] != -1 {
fl++
}
mut fr := fl
for fr < compact.len && compact[fr] == -1 {
fr++
}
if fr > l {
r = l - 1
continue outer
}
available := fr - fl
if available >= file_len {
break
}
fl = fr
}

for i in 0 .. file_len {
compact[fl + i] = compact[r]
compact[l + i] = -1
}
}

print_layout(compact)

println('part2: ${checksum(compact)}')
}

fn print_layout(layout []int) {
for value in layout {
if value != -1 {
print(value)
} else {
print('.')
}
}
print('\n')
}

fn checksum(layout []int) i64 {
mut total := i64(0)
for i, value in layout {
if value != -1 {
total += value * i
}
}
return total
}
Empty file removed known/2024/09/.gitkeep
Empty file.
5 changes: 5 additions & 0 deletions known/2024/09/leodev.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
00...111...2...333.44.5555.6666.777.888899
0099811188827773336446555566..............
part1: 1928
00992111777.44.333....5555.6666.....8888..
part2: 2858

0 comments on commit 5a91ed4

Please sign in to comment.