Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Scalaskel en java
package fr.ybonnel.codestory.path.scalaskel;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Change {
@JsonProperty
private Integer foo;
@JsonProperty
private Integer bar;
@JsonProperty
private Integer qix;
@JsonProperty
private Integer baz;
public Change(Change change) {
if (change != null) {
foo = change.foo;
bar = change.bar;
qix = change.qix;
baz = change.baz;
}
}
public void pay(Coin coin) {
switch (coin) {
case FOO:
foo = foo == null ? 1 : foo + 1;
break;
case BAR:
bar = bar == null ? 1 : bar + 1;
break;
case QIX:
qix = qix == null ? 1 : qix + 1;
break;
case BAZ:
baz = baz == null ? 1 : baz + 1;
break;
}
}
}
package fr.ybonnel.codestory.path.scalaskel;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
public enum Coin {
FOO(1),
BAR(7),
QIX(11),
BAZ(21);
private int value;
Coin(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public boolean canPay(int cents) {
return cents >= value;
}
private static class ListHolder {
private static final List<Coin> valuesAsLists = newArrayList(values());
}
public static List<Coin> valuesAsLists() {
return ListHolder.valuesAsLists;
}
}
package fr.ybonnel.codestory.path.scalaskel;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import java.util.List;
public enum ScalaskelChangeService {
INSTANCE;
public static ScalaskelChangeService getInstance() {
return INSTANCE;
}
public List<Change> calculateChanges(int cents) {
return completeChanges(cents, null, null);
}
private List<Change> completeChanges(int cents, Change currentChange, Coin lastCoin) {
// Stop condition of recursivity
if (cents == 0) {
return Lists.newArrayList(currentChange);
}
List<Change> changes = Lists.newArrayList();
for (Coin coin : Collections2.filter(
Coin.valuesAsLists(),
new FilterCoins(lastCoin, cents))) {
Change change = new Change(currentChange);
change.pay(coin);
changes.addAll(completeChanges(cents - coin.getValue(), change, coin));
}
return changes;
}
/**
* Filter coins with this rule :
* coin is keeped only if :
* <ul>
* <li>its value is bigger or equals thant lastCoin</li>
* <li>we can pay with the coin.</li>
* </ul>
*/
private static class FilterCoins implements Predicate<Coin> {
private int minValue;
private int centsToPay;
private FilterCoins(Coin lastCoin, int centsToPay) {
minValue = lastCoin == null ? 0 : lastCoin.getValue();
this.centsToPay = centsToPay;
}
@Override
public boolean apply(Coin input) {
return minValue <= input.getValue() && input.canPay(centsToPay);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment