code.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. func readNumbers(line string) []int {
  11. var numbers []int
  12. numbersStrings := strings.Split(line, ",")
  13. for _, numberString := range numbersStrings {
  14. if number, err := strconv.Atoi(numberString); err == nil {
  15. numbers = append(numbers, number)
  16. } else {
  17. log.Fatal("Numbers: ", err)
  18. }
  19. }
  20. return numbers
  21. }
  22. func readRow(line string) []int {
  23. var numbers []int
  24. numbersStrings := strings.Split(line, " ")
  25. fmt.Println(numbersStrings)
  26. for _, numberString := range numbersStrings {
  27. if numberString == "" {
  28. continue
  29. }
  30. if number, err := strconv.Atoi(numberString); err == nil {
  31. numbers = append(numbers, number)
  32. } else {
  33. log.Fatal("Row: ", err, numberString)
  34. }
  35. }
  36. return numbers
  37. }
  38. type Number struct {
  39. Val int
  40. Marked bool
  41. }
  42. func readInput(file *os.File) ([][][]Number, []int) {
  43. scanner := bufio.NewScanner(file)
  44. numbersRead := false
  45. var numbers []int
  46. var boards [][][]Number
  47. boardIndex := 0
  48. rowIndex := 0
  49. for scanner.Scan() {
  50. line := scanner.Text()
  51. if line == "" {
  52. continue
  53. }
  54. if !numbersRead {
  55. numbers = readNumbers(line)
  56. numbersRead = true
  57. continue
  58. }
  59. if rowIndex == 0 {
  60. boards = append(boards, make([][]Number, 5))
  61. }
  62. boards[boardIndex][rowIndex] = make([]Number, 5)
  63. fmt.Println(line)
  64. numbersInRow := readRow(line)
  65. for i, number := range numbersInRow {
  66. boards[boardIndex][rowIndex][i] = Number{number, false}
  67. }
  68. rowIndex++
  69. if rowIndex > 4 {
  70. rowIndex = 0
  71. boardIndex++
  72. }
  73. }
  74. if err := scanner.Err(); err != nil {
  75. log.Fatalf("Scanner error: %s", err)
  76. }
  77. return boards, numbers
  78. }
  79. func main() {
  80. if len(os.Args) < 2 {
  81. log.Fatal("You need to specify a file!")
  82. }
  83. filePath := os.Args[1]
  84. file, err := os.Open(filePath)
  85. if err != nil {
  86. log.Fatalf("Failed to open %s!\n", filePath)
  87. }
  88. boards, numbers := readInput(file)
  89. fmt.Println(boards, numbers)
  90. }