Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Day5 extends Solution {
- public Day5() {
- part1(this.input);
- part2(this.input);
- }
- @Override
- protected void part1(List<String> input) {
- List<Tuple> ranges = new ArrayList<>();
- List<Long> products = new ArrayList<>();
- int i = 0;
- while (!input.get(i).isBlank()) {
- String[] split = input.get(i).split("-");
- ranges.add(
- new Tuple(Long.valueOf(split[0]), Long.valueOf(split[1]))
- );
- i += 1;
- }
- i += 1;
- for (; i < input.size(); i++) {
- products.add(Long.valueOf(input.get(i)));
- }
- int result = 0;
- for (long product : products) {
- for (Tuple range : ranges) {
- if (range.inRange(product)) {
- result += 1;
- break;
- }
- }
- }
- System.out.println(result);
- }
- @Override
- protected void part2(List<String> input) {
- List<Tuple> ranges = new ArrayList<>();
- int i = 0;
- while (!input.get(i).isBlank()) {
- String[] split = input.get(i).split("-");
- ranges.add(
- new Tuple(Long.valueOf(split[0]), Long.valueOf(split[1]))
- );
- i += 1;
- }
- ranges.sort((r1, r2) -> {
- return Long.compare(r1.i, r2.i);
- });
- long result = 0;
- Tuple prev = ranges.get(0);
- for (i = 1; i < ranges.size(); i++) {
- Tuple curr = ranges.get(i);
- if (prev.inRange(curr.i)) {
- Tuple updated = new Tuple(
- Math.min(prev.i, curr.i),
- Math.max(prev.j, curr.j)
- );
- prev = updated;
- } else {
- result += prev.j - prev.i + 1;
- prev = curr;
- }
- }
- result += prev.j - prev.i + 1;
- System.out.println(result);
- }
- public static void main(String[] args) {
- Day5 day5 = new Day5();
- }
- }
- class Tuple {
- public final long i;
- public final long j;
- public Tuple(long i, long j) {
- this.i = i;
- this.j = j;
- }
- public boolean inRange(long product) {
- return i <= product && product <= j;
- }
- @Override
- public String toString() {
- return this.i + " " + this.j;
- }
- // Add equals(), hashCode(), toString() methods manually or via IDE
- }
Advertisement
Add Comment
Please, Sign In to add comment