|
@@ -83,6 +83,74 @@ func part1(diskMap []int) int64 {
|
|
|
return calculateChecksum(compacted)
|
|
|
}
|
|
|
|
|
|
+func findFile(disk []int, id, end int) int {
|
|
|
+ for i := end; i > 0; i-- {
|
|
|
+ if disk[i] != id {
|
|
|
+ return i + 1
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return -1
|
|
|
+}
|
|
|
+
|
|
|
+func findFree(disk []int, start, end, goal int) (int, int) {
|
|
|
+ var freeStart, freeEnd int
|
|
|
+ for i := start; i < end; i++ {
|
|
|
+ if disk[i] == -1 {
|
|
|
+ if freeStart <= 0 {
|
|
|
+ freeStart = i
|
|
|
+ for j := freeStart + 1; j < freeStart+goal; j++ {
|
|
|
+ if disk[i] != -1 {
|
|
|
+ freeStart = -1
|
|
|
+ i = j
|
|
|
+ break
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ if freeStart > 0 {
|
|
|
+ return freeStart, freeStart + goal
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return freeStart, freeEnd
|
|
|
+}
|
|
|
+
|
|
|
+func defrag(diskMap []int) []int {
|
|
|
+ free, disk := getDisk(diskMap)
|
|
|
+ end := len(disk) - 1
|
|
|
+
|
|
|
+ for i := end; i > free; i-- {
|
|
|
+ if disk[i] > 0 {
|
|
|
+ fileStart := findFile(disk, disk[i], i)
|
|
|
+ if fileStart > 0 {
|
|
|
+ freeStart, freeEnd := findFree(disk, free, fileStart, i-fileStart+1)
|
|
|
+ fmt.Println(i, disk[i], freeStart, freeEnd)
|
|
|
+ if freeStart > 0 && freeEnd > 0 && freeStart < freeEnd {
|
|
|
+ for k := freeStart; k < freeEnd; k++ {
|
|
|
+ disk[k] = disk[i]
|
|
|
+ }
|
|
|
+
|
|
|
+ for k := fileStart; k <= i; k++ {
|
|
|
+ disk[k] = -1
|
|
|
+ }
|
|
|
+
|
|
|
+ i = fileStart
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return disk
|
|
|
+}
|
|
|
+
|
|
|
+func part2(diskMap []int) int64 {
|
|
|
+ fmt.Println(defrag(diskMap))
|
|
|
+
|
|
|
+ return 0
|
|
|
+}
|
|
|
+
|
|
|
func main() {
|
|
|
if len(os.Args) < 2 {
|
|
|
log.Fatal("You need to specify a file!")
|
|
@@ -95,4 +163,5 @@ func main() {
|
|
|
|
|
|
diskMap := getDiskMap(data)
|
|
|
fmt.Println("Part1:", part1(diskMap))
|
|
|
+ fmt.Println("Part2:", part2(diskMap))
|
|
|
}
|