|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | +) |
| 8 | + |
| 9 | +func main() { |
| 10 | + fs := loadFS() |
| 11 | + fs.Defrag() |
| 12 | + fmt.Println(fs.Checksum()) |
| 13 | +} |
| 14 | + |
| 15 | +func loadFS() FS { |
| 16 | + scanner := bufio.NewScanner(os.Stdin) |
| 17 | + scanner.Scan() |
| 18 | + line := scanner.Text() |
| 19 | + |
| 20 | + files := make(map[int]*Block) |
| 21 | + freeSpace := make([]*Block, 0, len(line)/2) |
| 22 | + |
| 23 | + cursor := 0 |
| 24 | + for i, c := range line { |
| 25 | + num := int(c - '0') |
| 26 | + |
| 27 | + if i&1 == 0 { |
| 28 | + // on odd indexes, it's a file |
| 29 | + id := i / 2 |
| 30 | + files[id] = &Block{ |
| 31 | + ID: id, |
| 32 | + Start: cursor, |
| 33 | + End: cursor + num, |
| 34 | + } |
| 35 | + id++ |
| 36 | + } else { |
| 37 | + // on even indexes, it's free space |
| 38 | + freeSpace = append(freeSpace, &Block{ |
| 39 | + ID: -1, |
| 40 | + Start: cursor, |
| 41 | + End: cursor + num, |
| 42 | + }) |
| 43 | + } |
| 44 | + |
| 45 | + cursor += num |
| 46 | + } |
| 47 | + |
| 48 | + return FS{ |
| 49 | + Files: files, |
| 50 | + FreeSpace: freeSpace, |
| 51 | + MaxFileID: len(line) / 2, |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +type Block struct { |
| 56 | + ID, Start, End int |
| 57 | +} |
| 58 | + |
| 59 | +func (b Block) Size() int { |
| 60 | + return b.End - b.Start |
| 61 | +} |
| 62 | + |
| 63 | +type FS struct { |
| 64 | + Files map[int]*Block |
| 65 | + FreeSpace []*Block |
| 66 | + MaxFileID int |
| 67 | +} |
| 68 | + |
| 69 | +func (fs FS) Defrag() { |
| 70 | + for toMove := fs.MaxFileID; toMove >= 0; toMove-- { |
| 71 | + f := fs.Files[toMove] |
| 72 | + |
| 73 | + for i := 0; i < len(fs.FreeSpace); i++ { |
| 74 | + currEmpty := fs.FreeSpace[i] |
| 75 | + |
| 76 | + // Has to be big enough |
| 77 | + if currEmpty.Size() < f.Size() { |
| 78 | + continue |
| 79 | + } |
| 80 | + |
| 81 | + // Do not move to the right |
| 82 | + if currEmpty.Start > f.Start { |
| 83 | + break |
| 84 | + } |
| 85 | + |
| 86 | + // Found a valid empty space. Move file |
| 87 | + f.Start, f.End = currEmpty.Start, currEmpty.Start+f.Size() |
| 88 | + currEmpty.Start += f.Size() |
| 89 | + |
| 90 | + // If the emptySpace doesn't exist anymore, clean it up |
| 91 | + if currEmpty.Size() == 0 { |
| 92 | + fs.FreeSpace = append(fs.FreeSpace[:i], fs.FreeSpace[i+1:]...) |
| 93 | + } |
| 94 | + |
| 95 | + // After the file is moved, go to the next file |
| 96 | + break |
| 97 | + } |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +func (fs FS) Checksum() int { |
| 102 | + sum := 0 |
| 103 | + for _, f := range fs.Files { |
| 104 | + for i := f.Start; i < f.End; i++ { |
| 105 | + sum += f.ID * i |
| 106 | + } |
| 107 | + } |
| 108 | + return sum |
| 109 | +} |
0 commit comments