Skip to content

Instantly share code, notes, and snippets.

@msx80
Last active December 1, 2023 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msx80/00a2cb5b08de4743210d962829a790d1 to your computer and use it in GitHub Desktop.
Save msx80/00a2cb5b08de4743210d962829a790d1 to your computer and use it in GitHub Desktop.
package aoc2023;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
public class Day1 {
public static void main(String[] args) throws Exception
{
part1();
part2();
}
private static void part1() throws IOException {
int sum = Files
.readAllLines(Path.of("input1.txt"))
.stream()
.map(s -> s.replaceAll("\\D+",""))
.mapToInt(s -> Integer.parseInt(s.charAt(0)+""+s.charAt(s.length()-1)))
.sum();
System.out.println(sum);
}
static Map<String, String> numbers = Map.of(
"one", "1",
"two", "2",
"three", "3",
"four", "4",
"five", "5",
"six", "6",
"seven", "7",
"eight", "8",
"nine", "9"
) ;
private static String extractNumbers(String in)
{
String out = "";
for (int i = 0; i < in.length(); i++)
if(Character.isDigit(in.charAt(i)))
out+=in.charAt(i);
else
for (var e : numbers.entrySet())
if(in.indexOf(e.getKey(), i) == i)
out+=e.getValue();
return out;
}
private static void part2() throws IOException {
int sum = Files
.readAllLines(Path.of("input1.txt"))
.stream()
.map(Day1::extractNumbers)
.mapToInt(s -> Integer.parseInt(s.charAt(0)+""+s.charAt(s.length()-1)))
.sum();
System.out.println(sum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment