code.go 1.1 KB

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