Campbell Ritchie wrote:Presumably it would make no significant difference to the performance of your first method if you passed an int instead of the long. Probably no difference to the other two, either.
Certainly would not have made any difference in #1. For #2 an #3 I would have had to introduce a mapToLong() so that the reduce() could accumulate a long. This would result in each character in the string being converted 13 times. In the end, probably not significant. The skip/limit approach was definitely a problem and resulted in non-linear scaling.
Edit: This is just a curiosity for me at this point. The problem domain is so small as to make efforts to optimize it for performance insignificant. However, I view this as an opportunity to learn so that I have a better grasp for when the time comes to implement stream processing for a problem domain where it would make a difference.
I hinted at some optimization a couple of replies ago, but the reactions were such that the set of people interested probably equals the empty set.
And as Carey remarked, it is a waste of time trying to be smart for such a small problem.
But optimizing is sometimes more interesting than the problem itself. So here goes.
Let S0 be the product of the first 13 digits of, what Dana called, bigNumber.
So, S0 = d0 * d1 * d2 * ... * d12.
The product of the next 13 digits, S1, is: d1 * d2 * ... * d12 * d13. or: S1 = S0 * d13 / d0.
And so is S2 = S1 * d14 / d1, et cetera.
This resembles an iteration.
1) suppose that bigNumber does not contain any '0''s. We could then say:
Now, this 'alpha' is of the form d(i + 13) / d(i), so how to get this dynamic factor into the longstrean?
2) now, unfortunately, bigNumber does contain a lot of '0', totally ruining the above scheme.
Can you think of a simple way to deal with this problem, at the same time optimizing the excersize even further?
I must confess that for this, I used plain old java 7, since java 8 really got complicated.
Here's my highly optimized but convoluted method in Java 7. I think it is along the lines you were mentioning. First, compute the product of 13 numbers. Then, slide the window one number and compute prod = prod / number[i] * number[i+13]. Where this gets tricky is that when a zero is encountered it will skip to the next number past the zero and refill the buffer. I haven't timed this yet but the number of divides and multiplies it performs is 1,132 whereas the normal processing has 12,844.
My version 3 takes about half the time of the simple version 1 approach.