Day 9 implementation in Java
parent
cfb6d09af2
commit
c4d41f6643
|
|
@ -0,0 +1,45 @@
|
||||||
|
package day9;
|
||||||
|
|
||||||
|
import io.vavr.collection.List;
|
||||||
|
import util.FileReader;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
public class Main {
|
||||||
|
private static final boolean IS_PREDICTING_PREVIOUS_VALUES = true;
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String inputFilePath = System.getProperty("user.dir") + "\\java\\src\\main\\java\\day9\\input.txt";
|
||||||
|
FileReader reader = new FileReader(inputFilePath);
|
||||||
|
List<String> inputData = List.ofAll(reader.readContents());
|
||||||
|
|
||||||
|
Long predictionsSum = inputData
|
||||||
|
.map(string -> string.split(" "))
|
||||||
|
.map(splitString -> List.of(splitString).map(Long::parseLong))
|
||||||
|
.map(Main::predictValue)
|
||||||
|
.reduce(Long::sum);
|
||||||
|
|
||||||
|
System.out.println(predictionsSum);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Long predictValue(List<Long> values) {
|
||||||
|
if (values.filter(value -> value != 0L).isEmpty()) {
|
||||||
|
return 0L;
|
||||||
|
}
|
||||||
|
|
||||||
|
Integer predictionIndex = IS_PREDICTING_PREVIOUS_VALUES ? 0 : values.length() - 1;
|
||||||
|
Integer predictionSign = IS_PREDICTING_PREVIOUS_VALUES ? -1 : +1;
|
||||||
|
|
||||||
|
List<Long> reducedValues = getDifferencesList(values);
|
||||||
|
|
||||||
|
return values.get(predictionIndex) + (predictionSign * predictValue(reducedValues));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Long> getDifferencesList(List<Long> values) {
|
||||||
|
java.util.List<Long> differencesList = new ArrayList<>();
|
||||||
|
for (int i = 1; i < values.length(); i++) {
|
||||||
|
differencesList.add(values.get(i) - values.get(i-1));
|
||||||
|
}
|
||||||
|
return List.ofAll(differencesList);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue