Created
August 11, 2020 05:38
-
-
Save noel-yap/925dfc5b7e3811de3b9e69b8b856809e to your computer and use it in GitHub Desktop.
Coin Sums: https://projecteuler.net/problem=31
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
enum Coin { | |
ONE_P(1), | |
TWO_P(2), | |
FIVE_P(5), | |
TEN_P(10), | |
TWENTY_P(20), | |
FIFTY_P(50), | |
ONE_L(100), | |
TWO_L(200); | |
public int value; | |
Coin(final int value) { | |
this.value = value; | |
} | |
} | |
class Purse { | |
public final Map<Coin, Integer> coins; | |
public Purse() { | |
this.coins = new ConcurrentHashMap<Coin, Integer>(); | |
} | |
public Purse(final Purse rhs) { | |
this.coins = new ConcurrentHashMap<Coin, Integer>(rhs.coins); | |
} | |
public Purse putInto(final Coin coin) { | |
final Integer current = coins.getOrDefault(coin, 0); | |
coins.put(coin, current + 1); | |
return this; | |
} | |
} | |
public class Solution { | |
final Map<Integer, Set<Purse>> memo = new ConcurrentHashMap<Integer, Set<Purse>>(); | |
private Set<Purse> getPurses(final Purse purse, final int amount) { | |
final Set<Purse> pursesMemo = memo.get(amount); | |
if (pursesMemo != null) { | |
return pursesMemo; | |
} | |
if (amount == 0) { | |
return Collections.singleton(purse); | |
} else { | |
final Set<Purse> purses = new HashSet<Purse>(); | |
for (Coin coin : Coin.values()) { | |
if (coin.value > amount) { | |
break; | |
} | |
purses.addAll(getPurses(new Purse(purse).putInto(coin), 0)); | |
purses.addAll(getPurses(purse, amount - coin.value)); | |
} | |
memo.put(amount, purses); | |
return purses; | |
} | |
} | |
@Test | |
public void eyeballTest() { | |
System.out.println(getPurses(new Purse(), 200).size()); | |
} | |
public static void main(String[] args) { | |
JUnitCore.main("Solution"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment