I want to write this algorithm from JS to Java and I am having some problem doing it because Java does not support parameter defaults and does not do dynamic inputs. I know this must be somehow possible and even better written in a typed language but I dont know how. Please help Java Gods.
The algorithm is supposed to go through the array, and add it up and multiply each part by the depth that its at.
So something like
[1, 2]
would be something like
(1 * 1) + (2 * 1)
.Something at depth
[1, 2, [3, 4] ]
would be:
(1 * 1) + (2 * 1). + (( 3 + 4) *2)
As far as I understand anyways
Link for JS version of algorithm:
class ProductSum{ constructor() { } solution(array, multiplier = 1) { let sum = 0; for (let i = 0; i < array.length; i++) { if (array[i] instanceof Array) { += this.solution (array[i], multiplier + 1) sum } else { = sum + array[i]; sum } }return sum * multiplier; } } const myArray = [5, 2, [7, -1], 3, [6, [-13, 8], 4]]; let mySolution = new ProductSum(); let result = mySolution.solution(myArray); console.log(result);
So for java, first you need to represent this "type" of data in some way. You have a List of either single numbers or other Lists containing the same.
You can represent this like so
interface NestedNumberList {
sealed SingleNumber(int x)
record implements NestedNumberList {}
MultipleNumbers(List<NestedNumberList> numbers)
record implements NestedNumberList {}
}
Which you should read as a NestedNumberList
is one of SingleNumber
or MultipleNumbers
.
which makes your example data look like this
[5, 2, [7, -1], 3, [6, [-13, 8], 4]]
= new MultipleNumbers(List.of(
var myArray new SingleNumber(5),
new SingleNumber(2),
new MultipleNumbers(List.of(
new SingleNumber(7),
new SingleNumber(-1)
)),
new SingleNumber(3),
new MultipleNumbers(List.of(
new SingleNumber(6),
new MultipleNumbers(List.of(
new SingleNumber(-13),
new SingleNumber(8)
)),
new SingleNumber(4);
));
));
Which yes, is way more verbose, but lets not dwell on that. This is a bit of a pathological case.
class ProductSum {
int solution(MultipleNumbers array, int multiplier) {
int sum = 0;
for (var num : array.numbers()) {
switch (num) {
case SingleNumber single -> {
= sum + single.x();
sum }
case MultipleNumbers multiple -> {
+= this.solutionHelper(multiple, multiplier + 1);
sum }
}
}
return sum * multiplier;
}
int solution(MultipleNumbers array) {
return this.solution(array, 1);
}
}
System.out.println(new ProductSum().solution(myArray));
So thats roughly conceptually equivalent. (for Java 17 with preview features). For the default multiplier value, in this case we emulate that with method overloading.