aoc2024/day-09/internal/one/disk.go

60 lines
905 B
Go
Raw Normal View History

2024-12-10 21:42:26 +00:00
package one
import (
"fmt"
"slices"
"strings"
)
type disk struct {
data []int
totalUsed int
}
func newDisk(blocks []block) disk {
var totalUsed int
data := []int{}
for id, block := range blocks {
for range block.used {
data = append(data, id)
}
for range block.free {
data = append(data, empty)
}
totalUsed += block.used
}
return disk{
data: data,
totalUsed: totalUsed,
}
}
func (d *disk) len() int {
return d.totalUsed
}
func (d *disk) sort() {
for i := len(d.data) - 1; i >= 0; i-- {
if d.data[i] != empty {
indx := slices.Index(d.data, empty)
if indx == d.len() {
break
}
d.data[i], d.data[indx] = d.data[indx], d.data[i]
}
}
}
func (d *disk) debug() string {
var sb strings.Builder
for _, n := range d.data {
if n == empty {
sb.WriteRune('.')
} else {
sb.WriteString(fmt.Sprintf("%d", n))
}
}
return sb.String()
}