Skip to content

Commit

Permalink
day9p1
Browse files Browse the repository at this point in the history
  • Loading branch information
gamersi committed Dec 9, 2024
1 parent 7155ea7 commit 6e289ef
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
68 changes: 68 additions & 0 deletions day09p1/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package day09p1

import (
"io"
"strconv"

"aoc/utils"
)

func Solve(r io.Reader) any {
lines := utils.ReadLines(r)
line := lines[0]

return chksum(defrag(line))
}

func defrag(input string) []int {
var result []int

id := 0

for i, c := range input {
convInt, _ := strconv.Atoi(string(c))
storageblock := i % 2 == 0
for j := 0; j < convInt; j++ {
if storageblock {
result = append(result, id)
} else {
result = append(result, -1)
}
}
if storageblock {
id++
}
}

for i := len(result)-1; i > 0; i-- {
if result[i] != -1 {
firstEmpty := -1
for j := 0; j < len(result); j++ {
if result[j] == -1 {
firstEmpty = j
break
}
}
if firstEmpty != -1 && firstEmpty < i {
result[firstEmpty] = result[i]
result[i] = -1
} else {
break
}
}
}

return result
}

func chksum(input []int) int {
sum := 0

for i, id := range input {
if id != -1 {
sum += i * id
}
}

return sum
}
33 changes: 33 additions & 0 deletions day09p1/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package day09p1

import (
"strings"
"testing"

"aoc/utils"
)

var testInput = `2333133121414131402`

func TestSolve(t *testing.T) {
tests := []struct {
input string
answer int
}{
{testInput, 1928},
}

if testing.Verbose() {
utils.Verbose = true
}

for _, test := range tests {
r := strings.NewReader(test.input)

result := Solve(r).(int)

if result != test.answer {
t.Errorf("Expected %d, got %d", test.answer, result)
}
}
}

0 comments on commit 6e289ef

Please sign in to comment.