code.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. )
  11. func readInput(file string) (map[int]int, []int) {
  12. content, err := ioutil.ReadFile(file)
  13. if err != nil {
  14. log.Fatal(err)
  15. }
  16. numberStrings := strings.Split(string(content), ",")
  17. crabs := make(map[int]int)
  18. var orderedCrabs []int
  19. for _, numberString := range numberStrings {
  20. if numberString == "" {
  21. continue
  22. }
  23. if number, err := strconv.Atoi(numberString); err == nil {
  24. if _, ok := crabs[number]; !ok {
  25. orderedCrabs = append(orderedCrabs, number)
  26. }
  27. crabs[number]++
  28. } else {
  29. log.Fatal(err)
  30. }
  31. }
  32. sort.Ints(orderedCrabs)
  33. return crabs, orderedCrabs
  34. }
  35. func costPart1(steps int, value int) int {
  36. return steps * value
  37. }
  38. func costPart2(steps int, value int) int {
  39. cost := 0
  40. for i := 0; i < steps; i++ {
  41. cost += (i + 1) * value
  42. }
  43. return cost
  44. }
  45. func calculate(crabs map[int]int, orderedCrabs []int, cost func(int, int) int) int {
  46. shortest := 1000000000
  47. max := orderedCrabs[len(orderedCrabs)-1]
  48. for crab := orderedCrabs[0]; crab <= max; crab++ {
  49. route := 0
  50. for key, value := range crabs {
  51. if key == crab {
  52. continue
  53. }
  54. steps := 0
  55. if key < crab {
  56. steps = crab - key
  57. } else {
  58. steps = key - crab
  59. }
  60. route += cost(steps, value)
  61. }
  62. if route < shortest {
  63. shortest = route
  64. }
  65. }
  66. return shortest
  67. }
  68. func main() {
  69. if len(os.Args) < 2 {
  70. log.Fatal("Please provide a file name as argument")
  71. }
  72. crabs, orderedCrabs := readInput(os.Args[1])
  73. fmt.Println("Part1: ", calculate(crabs, orderedCrabs, costPart1))
  74. fmt.Println("Part2: ", calculate(crabs, orderedCrabs, costPart2))
  75. }