94 lines
1.8 KiB
Go
94 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"os"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
|
|
// general util
|
|
func check(e error) {
|
|
if e != nil { panic(e) }
|
|
}
|
|
|
|
func pop(arr []int, index *int) int {
|
|
/* get last element that is not a -1 and replacing it with -1 int the source slice */
|
|
for i := len(arr) - 1; i >= 0; i-- {
|
|
if arr[i] != -1 {
|
|
(*index) = i
|
|
elem := arr[i]
|
|
arr[i] = -1
|
|
return elem
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
func insert(arr []int, n int) int {
|
|
/* insert element at the first -1, return the index of this -1 */
|
|
for i, elem := range arr {
|
|
if elem == -1 {
|
|
arr[i] = n
|
|
return i
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
// main loop
|
|
func main() {
|
|
|
|
// read in file
|
|
dat, err := os.ReadFile("data.txt")
|
|
check(err)
|
|
dat_str := strings.TrimSpace(string(dat))
|
|
|
|
// contruct input as int arr
|
|
input := make([]int, 0, len(dat_str))
|
|
mem_size := 0
|
|
for _, char := range []rune(dat_str) {
|
|
num, err := strconv.Atoi(string(char))
|
|
check(err)
|
|
mem_size += num
|
|
input = append(input, num)
|
|
}
|
|
|
|
// convert to actual memory representation
|
|
mem := make([]int, 0, mem_size)
|
|
is_file := true
|
|
file_id := 0
|
|
for _, elem := range input {
|
|
if is_file {
|
|
for range elem {
|
|
mem = append(mem, file_id)
|
|
}
|
|
file_id++
|
|
} else {
|
|
for range elem {
|
|
mem = append(mem, -1)
|
|
}
|
|
}
|
|
is_file = !is_file
|
|
}
|
|
|
|
// reorder
|
|
idx_pop := -1
|
|
idx_insert := -2
|
|
|
|
for idx_pop != idx_insert {
|
|
elem := pop(mem, &idx_pop)
|
|
idx_insert = insert(mem, elem)
|
|
}
|
|
|
|
// calc checksum
|
|
checksum := 0
|
|
for i, elem := range mem {
|
|
if elem == -1 { break }
|
|
checksum += i * elem
|
|
}
|
|
|
|
fmt.Println(checksum)
|
|
}
|