Day 1 implementation in Java - bugfix
parent
cd9d30fb33
commit
877d1c4fa5
|
|
@ -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.
|
||||
|
|
@ -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<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) {
|
||||
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<Integer> getIndexesOfAllSubstringOccurrences(String string, String substring) {
|
||||
List<Integer> indexes = new ArrayList<>();
|
||||
int index = string.indexOf(substring);
|
||||
while (index >= 0) {
|
||||
indexes.add(index);
|
||||
index = string.indexOf(substring, index + 1);
|
||||
}
|
||||
return indexes;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue