Day 1 implementation in Java - bugfix

main
MiguelMLorente 2023-12-02 12:21:45 +01:00
parent cd9d30fb33
commit 877d1c4fa5
2 changed files with 38 additions and 17 deletions

7
java/README.md Normal file
View File

@ -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.

View File

@ -2,12 +2,25 @@ package day1;
import util.FileReader; import util.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class Main { public class Main {
// Part 1 one of the problem has this flag set to false, while part 2 has it set to true // 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 boolean IS_NUMBER_SPELLING_ENABLED = true;
private static final HashMap<String, Character> SPELLED_NUMBERS = new HashMap<String, Character>() {{
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) { public static void main(String[] args) {
String inputFilePath = System.getProperty("user.dir") + "\\java\\src\\main\\java\\day1\\input.txt"; 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) { private static String replaceSpelledDigits(String string) {
return string StringBuilder newStringBuilder = new StringBuilder(string);
.replaceAll("oneight", "18") SPELLED_NUMBERS.keySet().stream()
.replaceAll("threeight", "38") .filter(string::contains)
.replaceAll("fiveight", "58") .forEach(number -> getIndexesOfAllSubstringOccurrences(string, number)
.replaceAll("nineight", "98") .forEach(index -> newStringBuilder.setCharAt(index, SPELLED_NUMBERS.get(number)))
.replaceAll("twone", "21") );
.replaceAll("eightwo", "82")
.replaceAll("eighthree", "83") return newStringBuilder.toString();
.replaceAll("one", "1") }
.replaceAll("two", "2")
.replaceAll("three", "3") private static List<Integer> getIndexesOfAllSubstringOccurrences(String string, String substring) {
.replaceAll("four", "4") List<Integer> indexes = new ArrayList<>();
.replaceAll("five", "5") int index = string.indexOf(substring);
.replaceAll("six", "6") while (index >= 0) {
.replaceAll("seven", "7") indexes.add(index);
.replaceAll("eight", "8") index = string.indexOf(substring, index + 1);
.replaceAll("nine", "9"); }
return indexes;
} }
} }