Last active
December 24, 2015 18:09
-
-
Save laurilehmijoki/6840530 to your computer and use it in GitHub Desktop.
Find the maximum product of five consecutive integers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In Haskell: https://gist.github.com/laurilehmijoki/6829074
In Clojure: https://gist.github.com/laurilehmijoki/6829426