|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "io" |
| 6 | + "strconv" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +func fs1(input io.Reader) (int, error) { |
| 11 | + scanner := bufio.NewScanner(input) |
| 12 | + var discs []Disc |
| 13 | + for scanner.Scan() { |
| 14 | + s := scanner.Text() |
| 15 | + idx := indexAll(s, " ") |
| 16 | + positions, err := strconv.Atoi(s[idx[2]+1 : idx[3]]) |
| 17 | + if err != nil { |
| 18 | + return 0, nil |
| 19 | + } |
| 20 | + position, err := strconv.Atoi(s[idx[10]+1 : len(s)-1]) |
| 21 | + if err != nil { |
| 22 | + return 0, nil |
| 23 | + } |
| 24 | + discs = append(discs, Disc{positions, position}) |
| 25 | + } |
| 26 | + |
| 27 | + for i := 0; ; i++ { |
| 28 | + if find(0, discs, 0, i+1) { |
| 29 | + return i, nil |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +func find(i int, discs []Disc, previousPosition int, time int) bool { |
| 35 | + if i == len(discs) { |
| 36 | + return true |
| 37 | + } |
| 38 | + |
| 39 | + position := discs[i].getPosition(time) |
| 40 | + if i != 0 && position != previousPosition { |
| 41 | + return false |
| 42 | + } |
| 43 | + |
| 44 | + return find(i+1, discs, position, time+1) |
| 45 | +} |
| 46 | + |
| 47 | +type Disc struct { |
| 48 | + positions int |
| 49 | + position int |
| 50 | +} |
| 51 | + |
| 52 | +func (d Disc) getPosition(time int) int { |
| 53 | + return (d.position + time) % d.positions |
| 54 | +} |
| 55 | + |
| 56 | +func indexAll(s string, search string) []int { |
| 57 | + i := 0 |
| 58 | + var res []int |
| 59 | + for i < len(s) { |
| 60 | + index := strings.Index(s[i:], search) |
| 61 | + if index == -1 { |
| 62 | + return res |
| 63 | + } |
| 64 | + res = append(res, index+i) |
| 65 | + i += index + len(search) |
| 66 | + } |
| 67 | + return res |
| 68 | +} |
| 69 | + |
| 70 | +func fs2(input io.Reader) (int, error) { |
| 71 | + scanner := bufio.NewScanner(input) |
| 72 | + var discs []Disc |
| 73 | + for scanner.Scan() { |
| 74 | + s := scanner.Text() |
| 75 | + idx := indexAll(s, " ") |
| 76 | + positions, err := strconv.Atoi(s[idx[2]+1 : idx[3]]) |
| 77 | + if err != nil { |
| 78 | + return 0, nil |
| 79 | + } |
| 80 | + position, err := strconv.Atoi(s[idx[10]+1 : len(s)-1]) |
| 81 | + if err != nil { |
| 82 | + return 0, nil |
| 83 | + } |
| 84 | + discs = append(discs, Disc{positions, position}) |
| 85 | + } |
| 86 | + discs = append(discs, Disc{11, 0}) |
| 87 | + |
| 88 | + for i := 0; ; i++ { |
| 89 | + if find(0, discs, 0, i+1) { |
| 90 | + return i, nil |
| 91 | + } |
| 92 | + } |
| 93 | +} |
0 commit comments