Created
October 27, 2011 16:39
-
-
Save kinow/1320080 to your computer and use it in GitHub Desktop.
Euler1
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
package euler; | |
import org.apache.commons.functor.UnaryPredicate; | |
import org.apache.commons.functor.UnaryProcedure; | |
import org.apache.commons.functor.core.composite.ConditionalUnaryProcedure; | |
import org.apache.commons.functor.generator.Generator; | |
import org.apache.commons.functor.generator.util.EachElement; | |
import org.apache.commons.functor.generator.util.IntegerRange; | |
/** | |
* An adder, or a summer, whatever. | |
* | |
* @author Bruno P. Kinoshita - http://www.kinoshita.eti.br | |
*/ | |
class Adder implements UnaryProcedure<Integer> { | |
private int total = 0; | |
public void run(Integer obj) { | |
if (obj != null) { | |
total = total + (obj.intValue()); | |
} | |
} | |
public int getTotal() { | |
return total; | |
} | |
} | |
/** | |
* Problem from Euler that loiane resolved in Java, now in Functional | |
* Programming :) | |
* | |
* I'm quite new to FP, so there may have other ways (maybe better) of using FP | |
* to solve this problem. | |
* | |
* @see {@link http://www.loiane.com/2011/10/project-euler-problema-1/} | |
* | |
* @author Bruno P. Kinoshita - http://www.kinoshita.eti.br | |
*/ | |
public class Euler1 { | |
// A predicate that represents our condition for this problem: a number | |
// is multiple of three (3) or five (5). | |
private static final UnaryPredicate<Integer> IS_MULTIPLE_OF_THREE_OR_FIVE = new UnaryPredicate<Integer>() { | |
public boolean test(Integer obj) { | |
if (obj != null) { | |
if (obj % 3 == 0 || obj % 5 == 0) { | |
return true; | |
} | |
} | |
return false; | |
} | |
}; | |
public int test(Integer left, Integer right){ | |
Generator<Integer> generator = EachElement.from(new IntegerRange(left, | |
right).toCollection()); // From 0 to 1 | |
Adder summer = new Adder(); // :-) We create an adder | |
ConditionalUnaryProcedure<Integer> proc = new ConditionalUnaryProcedure<Integer>( | |
IS_MULTIPLE_OF_THREE_OR_FIVE, summer); // And a procedure that | |
// executes another one | |
// if a condition is | |
// valid. | |
generator.run(proc); // Run our generator, executing the procedure above | |
return summer.getTotal(); // Return the total | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about this one: https://gist.github.com/1331277 ?
It has some features that the other solutions don't:
I initialized both candidates to be included in the sum with 0, but I could have just similarly have initialized them to 3 and 5, but this doesn't buy us anything good (one iteration of the body of a loop that is way lighter right now).
Comments?