Skip to content

Instantly share code, notes, and snippets.

@laurilehmijoki
Last active December 24, 2015 18:09
Show Gist options
  • Save laurilehmijoki/6840530 to your computer and use it in GitHub Desktop.
Save laurilehmijoki/6840530 to your computer and use it in GitHub Desktop.
Find the maximum product of five consecutive integers.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;
import static java.lang.Integer.parseInt;
import static java.util.Comparator.naturalOrder;
public class Test {
static final String nums = "37900490610897696126265185408732594047834333441947018503938074170641817003483791166860080189669498677558722248271653685006165703758078020538662914584106964490601037178417735301109842904952970798120105470168021976855478449620066905768943533366888238302291333721473491149055521813412305168905832929411783011983450277211542535458190375258738804563705619552777408744641552952789449531990152618001564228057277177446096431068469989305514445184509262635998279063901081322647763278370447051079759349248247518";
public static void main(String[] args) {
Stream<Stream<Integer>> partitioned = partition(nums, 5)
.stream()
.map((str) -> Arrays.asList(
str.charAt(0),
str.charAt(1),
str.charAt(2),
str.charAt(3),
str.charAt(4)
))
.map((chars) ->
chars
.stream()
.map((chr) -> parseInt(String.valueOf(chr)))
);
Integer max = partitioned
.map((stream) -> stream.reduce((a, b) -> a * b).get())
.max(naturalOrder())
.get();
System.out.println(max); // Will print 34992
}
static Collection<String> partition(String str, int partitionSize) {
Collection<String> partitions = new ArrayList<>();
for (int i = 0; i < str.length();) {
partitions.add(str.substring(i, i + partitionSize));
i = i + partitionSize;
}
return partitions;
}
}
@laurilehmijoki
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment