Day 9 part 1 done
This commit is contained in:
56
9/main.go
Normal file
56
9/main.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// file, _ := os.Open("test")
|
||||
file, _ := os.Open("input")
|
||||
defer file.Close()
|
||||
scanner := bufio.NewScanner(file)
|
||||
diskMap := []string{}
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
diskMap = append(diskMap, strings.Split(line, "")...)
|
||||
}
|
||||
fileID := 0
|
||||
blockSize := 0
|
||||
freeSpace := 0
|
||||
blocks := []string{}
|
||||
for i := range diskMap {
|
||||
if i % 2 == 0 {
|
||||
blockSize, _ = strconv.Atoi(diskMap[i])
|
||||
for j:=0;j<blockSize;j++ {
|
||||
blocks = append(blocks, strconv.Itoa(fileID))
|
||||
}
|
||||
fileID++
|
||||
} else {
|
||||
freeSpace, _ = strconv.Atoi(diskMap[i])
|
||||
for j:=0;j<freeSpace;j++ {
|
||||
blocks = append(blocks, ".")
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range blocks {
|
||||
if blocks[i] == "." {
|
||||
for j:=len(blocks)-1;j>i;j-- {
|
||||
if blocks[j] != "." {
|
||||
blocks[i] = blocks[j]
|
||||
blocks[j] = "."
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
checksum := 0
|
||||
for i := range blocks {
|
||||
blockID, _ := strconv.Atoi(blocks[i])
|
||||
checksum = checksum + i * blockID
|
||||
}
|
||||
fmt.Println(checksum)
|
||||
}
|
||||
Reference in New Issue
Block a user