From 877d1c4fa52121a5003439be2d90f74f517f4f9a Mon Sep 17 00:00:00 2001 From: MiguelMLorente Date: Sat, 2 Dec 2023 12:21:45 +0100 Subject: [PATCH] Day 1 implementation in Java - bugfix --- java/README.md | 7 +++++ java/src/main/java/day1/Main.java | 48 ++++++++++++++++++++----------- 2 files changed, 38 insertions(+), 17 deletions(-) create mode 100644 java/README.md diff --git a/java/README.md b/java/README.md new file mode 100644 index 0000000..e82ca83 --- /dev/null +++ b/java/README.md @@ -0,0 +1,7 @@ +### How to run? + +You need to have your JDK installed. I'll be using JDK-23. + +Run from IDE directly, as JAR files have not yet been created. + +Different problems are in different folders. Generally a variable contains the value that controlls whether the first sub-problem is executed or the second. \ No newline at end of file diff --git a/java/src/main/java/day1/Main.java b/java/src/main/java/day1/Main.java index 9cf568d..e34e87c 100644 --- a/java/src/main/java/day1/Main.java +++ b/java/src/main/java/day1/Main.java @@ -2,12 +2,25 @@ package day1; import util.FileReader; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; public class Main { // Part 1 one of the problem has this flag set to false, while part 2 has it set to true private static final boolean IS_NUMBER_SPELLING_ENABLED = true; + private static final HashMap SPELLED_NUMBERS = new HashMap() {{ + put("one", '1'); + put("two", '2'); + put("three", '3'); + put("four", '4'); + put("five", '5'); + put("six", '6'); + put("seven", '7'); + put("eight", '8'); + put("nine", '9'); + }}; public static void main(String[] args) { String inputFilePath = System.getProperty("user.dir") + "\\java\\src\\main\\java\\day1\\input.txt"; @@ -36,23 +49,24 @@ public class Main { } private static String replaceSpelledDigits(String string) { - return string - .replaceAll("oneight", "18") - .replaceAll("threeight", "38") - .replaceAll("fiveight", "58") - .replaceAll("nineight", "98") - .replaceAll("twone", "21") - .replaceAll("eightwo", "82") - .replaceAll("eighthree", "83") - .replaceAll("one", "1") - .replaceAll("two", "2") - .replaceAll("three", "3") - .replaceAll("four", "4") - .replaceAll("five", "5") - .replaceAll("six", "6") - .replaceAll("seven", "7") - .replaceAll("eight", "8") - .replaceAll("nine", "9"); + StringBuilder newStringBuilder = new StringBuilder(string); + SPELLED_NUMBERS.keySet().stream() + .filter(string::contains) + .forEach(number -> getIndexesOfAllSubstringOccurrences(string, number) + .forEach(index -> newStringBuilder.setCharAt(index, SPELLED_NUMBERS.get(number))) + ); + + return newStringBuilder.toString(); + } + + private static List getIndexesOfAllSubstringOccurrences(String string, String substring) { + List indexes = new ArrayList<>(); + int index = string.indexOf(substring); + while (index >= 0) { + indexes.add(index); + index = string.indexOf(substring, index + 1); + } + return indexes; } }