Advent of Code 2022: Day 4

Задачка, предложенная на четвёртом дне, снова показалась проще предыдущей. Если так пойдёт и дальше — можно успеть нагнать календарь и начать двигаться размеренно, по штуке в день.

Получилось так, что решается она практически целиком — копипастом решения первой половины во вторую (за исключением последнего .map. На циклах можно и не копипастить, пожалуй, но уже сделано так.

Главное — есть верный ответ!

static void day4(String puzzleInputUri) throws IOException, InterruptedException { var resultPartOne = client.send(request.uri((URI.create(puzzleInputUri))).build(), HttpResponse.BodyHandlers.ofLines()).body() .map(pair -> pair.split(",")) .map(tasks -> { String[] taskOneBounds = tasks[0].split("-"); String[] taskTwoBounds = tasks[1].split("-"); return Map.entry( Map.entry(Integer.parseInt(taskOneBounds[0]), Integer.parseInt(taskOneBounds[1])), Map.entry(Integer.parseInt(taskTwoBounds[0]), Integer.parseInt(taskTwoBounds[1])) ); }) .map(tasks -> Map.entry( IntStream.rangeClosed(tasks.getKey().getKey(), tasks.getKey().getValue()).boxed().collect(Collectors.toSet()), IntStream.rangeClosed(tasks.getValue().getKey(), tasks.getValue().getValue()).boxed().collect(Collectors.toSet()) )) .map(tasks -> { var task1 = new HashSet<>(tasks.getKey()); var task2 = new HashSet<>(tasks.getValue()); task1.removeAll(task2); tasks.getValue().removeAll(tasks.getKey()); return task1.isEmpty() || tasks.getValue().isEmpty(); }) .filter(included -> included) .count(); System.out.println(resultPartOne); var resultPartTwo = client.send(request.uri((URI.create(puzzleInputUri))).build(), HttpResponse.BodyHandlers.ofLines()).body() .map(pair -> pair.split(",")) .map(tasks -> { String[] taskOneBounds = tasks[0].split("-"); String[] taskTwoBounds = tasks[1].split("-"); return Map.entry( Map.entry(Integer.parseInt(taskOneBounds[0]), Integer.parseInt(taskOneBounds[1])), Map.entry(Integer.parseInt(taskTwoBounds[0]), Integer.parseInt(taskTwoBounds[1])) ); }) .map(tasks -> Map.entry( IntStream.rangeClosed(tasks.getKey().getKey(), tasks.getKey().getValue()).boxed().collect(Collectors.toSet()), IntStream.rangeClosed(tasks.getValue().getKey(), tasks.getValue().getValue()).boxed().collect(Collectors.toSet()) )) .map(tasks -> tasks.getKey().stream().anyMatch(taskN -> tasks.getValue().contains(taskN)) || tasks.getValue().stream().anyMatch(taskN -> tasks.getKey().contains(taskN)) ) .filter(cross -> cross) .count(); System.out.println(resultPartTwo); }
0
Комментарии
-3 комментариев
Раскрывать всегда