Created
April 20, 2011 13:20
-
-
Save tfnico/931313 to your computer and use it in GitHub Desktop.
Solving http://projecteuler.net/index.php?section=problems&id=1 being as functional as possible using Google Guava
This file contains 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
static int solution(int limit){ | |
ImmutableSet<Integer> numbers = intRange(1,limit); | |
return foldInsByAdding(Iterables.filter(numbers, dividableByThreeOrFive())); | |
} | |
private static Predicate<Integer> dividableByThreeOrFive(){ | |
return new Predicate<Integer>() { | |
@Override | |
public boolean apply(Integer i){ | |
return (i % 3 == 0) || (i % 5 == 0); | |
} | |
}; | |
} | |
/** | |
* I would've liked to have a Iterables.fold(integers, addFunction()), but not in guava yet. | |
* There is a fold in functionaljava.org though. | |
*/ | |
private static Integer foldInsByAdding(Iterable<Integer> ints){ | |
int sum = 0; | |
for (Integer i : ints){ | |
sum = sum + i; | |
} | |
return sum; | |
} | |
/** | |
* Guava does not have a Range thingie yet (but will get one this year). | |
*/ | |
private static ImmutableSet<Integer> intRange(int from, int to){ | |
Set<Integer> set = Sets.newHashSet(); | |
for(int i = from; i < to ; i++){ | |
set.add(Integer.valueOf(i)); | |
} | |
return ImmutableSet.copyOf(set); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment