So here's a simple algorithmic problem,
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without division and in O(n). For example, given [1,2,3,4], return [24,12,8,6].
Here's my solution,
public static int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
int leftProduct = 1;
int rightProduct = 1;
for(int i = 0; i < result.length; i++){
result[i] = leftProduct;
leftProduct *= nums[i];
}
for(int i=nums.length -1; i >= 0; i --){
result[i] *= rightProduct;
rightProduct *= nums[i];
}
return result;
}
public static void main(String[] args) {
int[] output = productExceptSelf(new int[]{1, 2, 3, 4});
Arrays.stream(output).forEach(System.out::println);
}
This works fine. What I'm trying to learn is how to rewrite this code in Java 8. As in what the different options with the loops in Java 8.
StreamAPI is not designed very well for this.System.out.println(Arrays.toString(output));is nicer looking.