Skip to content

Instantly share code, notes, and snippets.

@tfnico
Created April 20, 2011 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfnico/931313 to your computer and use it in GitHub Desktop.
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
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