|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "sort" |
| 6 | +) |
| 7 | + |
| 8 | +func main() { |
| 9 | + ranges, _ := parseInput() |
| 10 | + |
| 11 | + sort.Slice(ranges, func(i, j int) bool { |
| 12 | + if ranges[i].Start == ranges[j].Start { |
| 13 | + // when they have the same start, prefer bigger ranges on the left, |
| 14 | + // so `contains` will eat them at the beginning of the next loop |
| 15 | + return ranges[i].End > ranges[j].End |
| 16 | + } |
| 17 | + return ranges[i].Start < ranges[j].Start |
| 18 | + }) |
| 19 | + |
| 20 | + // index of the Work in Progress range |
| 21 | + wipIdx := 0 |
| 22 | + |
| 23 | + for i := 1; i < len(ranges); i++ { |
| 24 | + wipRange := ranges[wipIdx] |
| 25 | + |
| 26 | + // if the WIP contains the current, we ignore the current |
| 27 | + if wipRange.contains(ranges[i]) { |
| 28 | + continue |
| 29 | + } |
| 30 | + |
| 31 | + // if they touch, we merge them inside the WIP |
| 32 | + if wipRange.overlaps(ranges[i]) { |
| 33 | + ranges[wipIdx] = wipRange.append(ranges[i]) |
| 34 | + continue |
| 35 | + } |
| 36 | + |
| 37 | + // disjoint ranges |
| 38 | + // freeze the current WIP by focusing on the next one |
| 39 | + // that is the current range |
| 40 | + wipIdx++ |
| 41 | + ranges[wipIdx] = ranges[i] |
| 42 | + } |
| 43 | + |
| 44 | + ranges = ranges[:wipIdx+1] |
| 45 | + |
| 46 | + sum := 0 |
| 47 | + for _, r := range ranges { |
| 48 | + sum += r.Len() |
| 49 | + } |
| 50 | + |
| 51 | + fmt.Println(sum) |
| 52 | +} |
| 53 | + |
| 54 | +func (r Range) overlaps(r2 Range) bool { |
| 55 | + return r.Start <= r2.Start && r.End >= r2.Start |
| 56 | +} |
| 57 | + |
| 58 | +func (r Range) contains(r2 Range) bool { |
| 59 | + return r.Start <= r2.Start && r.End >= r2.End |
| 60 | +} |
| 61 | + |
| 62 | +func (r Range) append(r2 Range) Range { |
| 63 | + return Range{r.Start, r2.End} |
| 64 | +} |
| 65 | + |
| 66 | +func (r Range) Len() int { |
| 67 | + return r.End - r.Start + 1 |
| 68 | +} |
0 commit comments