djangofan :
I am playing around and trying to solve this problem "Two Sum" with a Java Stream, not using the imperative method:
Given nums = [2, 7, 11, 15], target = 18,
Because nums[1] + nums[2] = 7 + 11 = 18,
return [1, 2].
And here is my partially working code. Can anyone help solve? I just can't figure out how to collect it back up to be returned as a primitive int array :
class Solution {
public int[] twoSum(int[] input, int target) {
IntStream.range(0, input.length)
.forEach(i -> {
IntStream.range(0, input.length)
.filter(j -> i != j && input[i] + input[j] == target)
.peek(t -> System.out.println(input[t]))
.findFirst();
}
);
return null;
}
}
And here is the output of the above (coming from peek):
11
7
dehasi :
As I said in comments Streams are not always a perfect solution. But regarding your task, it looks like you need a stream of Pair. Unfortunately Java does not have Tuples (like Scala) that's why I suggest to create a simple Pair
class.
class Pair {
int i, j;
public Pair(int i, int j) {
this.i = i;
this.j = j;
}
}
Then, work with a stream of pairs
IntStream.range(0, input.length)
.boxed()
.flatMap(i -> IntStream.range(0, input.length).boxed()
.map(j -> new Pair(i,j))
)
.filter(p -> p.i != p.j)
.filter(p -> input[p.i] + input[p.j] == target)
.collect(toList());