code.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. )
  7. func getDiskMap(data []byte) []int {
  8. diskMap := make([]int, len(data))
  9. for i, block := range data {
  10. if block < 48 || block > 57 {
  11. continue
  12. }
  13. diskMap[i] = int(block) - 48
  14. }
  15. return diskMap
  16. }
  17. func getDisk(diskMap []int) (int, []int) {
  18. var disk []int
  19. file := true
  20. var fileID int
  21. for _, number := range diskMap {
  22. if file {
  23. file = false
  24. for j := 0; j < number; j++ {
  25. disk = append(disk, fileID)
  26. }
  27. fileID++
  28. } else {
  29. file = true
  30. for j := 0; j < number; j++ {
  31. disk = append(disk, -1)
  32. }
  33. }
  34. }
  35. return diskMap[0], disk
  36. }
  37. func compact(disk []int, free int) []int {
  38. end := len(disk) - 1
  39. for free < end {
  40. if disk[free] != -1 {
  41. free++
  42. continue
  43. }
  44. if disk[end] == -1 {
  45. end--
  46. continue
  47. }
  48. disk[free], disk[end] = disk[end], disk[free]
  49. free++
  50. end--
  51. }
  52. return disk
  53. }
  54. func calculateChecksum(disk []int) int64 {
  55. var checksum int64
  56. for i := range disk {
  57. if disk[i] != -1 {
  58. checksum += int64(disk[i] * i)
  59. }
  60. }
  61. return checksum
  62. }
  63. func part1(diskMap []int) int64 {
  64. free, disk := getDisk(diskMap)
  65. compacted := compact(disk, free)
  66. return calculateChecksum(compacted)
  67. }
  68. func main() {
  69. if len(os.Args) < 2 {
  70. log.Fatal("You need to specify a file!")
  71. }
  72. data, err := os.ReadFile(os.Args[1])
  73. if err != nil {
  74. log.Fatal(err)
  75. }
  76. diskMap := getDiskMap(data)
  77. fmt.Println("Part1:", part1(diskMap))
  78. }