Skip to content

Commit

Permalink
[2023] Solution for day 3
Browse files Browse the repository at this point in the history
  • Loading branch information
kfarnung committed Dec 3, 2023
1 parent aaff8c9 commit dc1d98b
Show file tree
Hide file tree
Showing 7 changed files with 445 additions and 1 deletion.
67 changes: 67 additions & 0 deletions 2023/day03/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Day 3: Gear Ratios

[https://adventofcode.com/2023/day/3](https://adventofcode.com/2023/day/3)

## Description

### Part One

You and the Elf eventually reach a [gondola lift](https://en.wikipedia.org/wiki/Gondola_lift) station; he says the gondola lift will take you up to the _water source_, but this is as far as he can bring you. You go inside.

It doesn't take long to find the gondolas, but there seems to be a problem: they're not moving.

"Aaah!"

You turn around to see a slightly-greasy Elf with a wrench and a look of surprise. "Sorry, I wasn't expecting anyone! The gondola lift isn't working right now; it'll still be a while before I can fix it." You offer to help.

The engineer explains that an engine part seems to be missing from the engine, but nobody can figure out which one. If you can _add up all the part numbers_ in the engine schematic, it should be easy to work out which part is missing.

The engine schematic (your puzzle input) consists of a visual representation of the engine. There are lots of numbers and symbols you don't really understand, but apparently _any number adjacent to a symbol_, even diagonally, is a "part number" and should be included in your sum. (Periods (`.`) do not count as a symbol.)

Here is an example engine schematic:

467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..


In this schematic, two numbers are _not_ part numbers because they are not adjacent to a symbol: `114` (top right) and `58` (middle right). Every other number is adjacent to a symbol and so _is_ a part number; their sum is _`4361`_.

Of course, the actual engine schematic is much larger. _What is the sum of all of the part numbers in the engine schematic?_

### Part Two

The engineer finds the missing part and installs it in the engine! As the engine springs to life, you jump in the closest gondola, finally ready to ascend to the water source.

You don't seem to be going very fast, though. Maybe something is still wrong? Fortunately, the gondola has a phone labeled "help", so you pick it up and the engineer answers.

Before you can explain the situation, she suggests that you look out the window. There stands the engineer, holding a phone in one hand and waving with the other. You're going so slowly that you haven't even left the station. You exit the gondola.

The missing part wasn't the only issue - one of the gears in the engine is wrong. A _gear_ is any `*` symbol that is adjacent to _exactly two part numbers_. Its _gear ratio_ is the result of <span title="They're magic gears.">multiplying</span> those two numbers together.

This time, you need to find the gear ratio of every gear and add them all up so that the engineer can figure out which gear needs to be replaced.

Consider the same engine schematic again:

467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..


In this schematic, there are _two_ gears. The first is in the top left; it has part numbers `467` and `35`, so its gear ratio is `16345`. The second gear is in the lower right; its gear ratio is `451490`. (The `*` adjacent to `617` is _not_ a gear because it is only adjacent to one part number.) Adding up all of the gear ratios produces _`467835`_.

_What is the sum of all of the gear ratios in your engine schematic?_
11 changes: 11 additions & 0 deletions 2023/day03/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
plugins {
id("com.github.kfarnung.adventofcode.aoc2023.java-application-conventions")
}

dependencies {
implementation(project(":utilities"))
}

application {
mainClass.set("com.github.kfarnung.adventofcode.aoc2023.day03.App")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* Solution for Advent of Code 2023 day 3.
*/
package com.github.kfarnung.adventofcode.aoc2023.day03;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.github.kfarnung.adventofcode.aoc2023.utilities.InputUtils.readLinesFromFile;

public class App {
public static void main(String[] args) {
try {
List<String> lines = readLinesFromFile(args[0]);
System.out.printf("Part 1: %s%n", getPart1(lines));
System.out.printf("Part 2: %s%n", getPart2(lines));
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getPart1(List<String> lines) {
List<List<Character>> rows = lines.stream()
.map(line -> line.chars().mapToObj(c -> (char) c).toList())
.toList();

long total = 0;
StringBuilder sb = new StringBuilder();
List<Part> symbols = new ArrayList<>();
for (int i = 0; i < rows.size(); i++) {
List<Character> row = rows.get(i);
for (int j = 0; j < row.size(); j++) {
Character c = row.get(j);
if (Character.isDigit(c)) {
sb.append(c);
for (Part symbol : findSymbols(rows, i, j)) {
symbols.add(symbol);
}
} else {
if (!symbols.isEmpty()) {
total += Integer.parseInt(sb.toString());
}

sb.setLength(0);
symbols.clear();
}
}
}

return Long.toString(total);
}

public static String getPart2(List<String> lines) {
List<List<Character>> rows = lines.stream()
.map(line -> line.chars().mapToObj(c -> (char) c).toList())
.toList();

Map<Part, List<Integer>> symbolMap = new HashMap<>();
StringBuilder sb = new StringBuilder();
Set<Part> symbols = new HashSet<>();
for (int i = 0; i < rows.size(); i++) {
List<Character> row = rows.get(i);
for (int j = 0; j < row.size(); j++) {
Character c = row.get(j);
if (Character.isDigit(c)) {
sb.append(c);
for (Part symbol : findSymbols(rows, i, j)) {
if (symbol.getSymbol() == '*') {
symbols.add(symbol);
}
}
} else {
for (Part symbol : symbols) {
symbolMap.computeIfAbsent(symbol, k -> new ArrayList<>()).add(Integer.parseInt(sb.toString()));
}

sb.setLength(0);
symbols.clear();
}
}
}

long total = 0;
for (List<Integer> values : symbolMap.values()) {
if (values.size() == 2) {
long product = 1;
for (Integer value : values) {
product *= value;
}

total += product;
}
}

return Long.toString(total);
}

private static Set<Part> findSymbols(List<List<Character>> rows, int x, int y) {
Set<Part> symbols = new HashSet<>();
for (int i = -1; i <= 1; i++) {
int rowIndex = x + i;
if (rowIndex < 0 || rowIndex >= rows.size()) {
continue;
}

List<Character> row = rows.get(rowIndex);

for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) {
continue;
}

int colIndex = y + j;
if (colIndex < 0 || colIndex >= rows.get(rowIndex).size()) {
continue;
}

Character c = row.get(colIndex);

if (!Character.isDigit(c) && c != '.') {
symbols.add(new Part(c, rowIndex, colIndex));
}
}
}

return symbols;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.github.kfarnung.adventofcode.aoc2023.day03;

public class Part {
private final char symbol;
private final int x;
private final int y;

public Part(char symbol, int x, int y) {
this.symbol = symbol;
this.x = x;
this.y = y;
}

public char getSymbol() {
return symbol;
}

public int getX() {
return x;
}

public int getY() {
return y;
}

@Override
public int hashCode() {
return x ^ y;
}

@Override
public boolean equals(Object obj) {
if (obj instanceof Part) {
Part other = (Part) obj;
return x == other.x && y == other.y;
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Test cases for Advent of Code 2023 day 3.
*/
package com.github.kfarnung.adventofcode.aoc2023.day03;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.junit.jupiter.api.Test;

import static com.github.kfarnung.adventofcode.aoc2023.utilities.InputUtils.readLinesFromResources;
import static org.junit.jupiter.api.Assertions.assertEquals;

class AppTest {
@Test
void testGetPart1() throws IOException {
List<String> lines = Arrays.asList(
"467..114..",
"...*......",
"..35..633.",
"......#...",
"617*......",
".....+.58.",
"..592.....",
"......755.",
"...$.*....",
".664.598..");
assertEquals("4361", App.getPart1(lines));

lines = readLinesFromResources(this, "input.txt");
assertEquals("512794", App.getPart1(lines));
}

@Test
void testGetPart2() throws IOException {
List<String> lines = Arrays.asList(
"467..114..",
"...*......",
"..35..633.",
"......#...",
"617*......",
".....+.58.",
"..592.....",
"......755.",
"...$.*....",
".664.598..");
assertEquals("467835", App.getPart2(lines));

lines = readLinesFromResources(this, "input.txt");
assertEquals("67779080", App.getPart2(lines));
}
}
Loading

0 comments on commit dc1d98b

Please sign in to comment.