Skip to content

Instantly share code, notes, and snippets.

@sczizzo
Created December 22, 2012 00:01
Show Gist options
  • Save sczizzo/4356657 to your computer and use it in GitHub Desktop.
Save sczizzo/4356657 to your computer and use it in GitHub Desktop.
Making change under ideal conditions
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class Change {
List<Integer> coins;
public Change(int numCoins, int[] rawCoins) {
ArrayList<Integer> coins = new ArrayList<Integer>(numCoins);
for (int i = 0; i < numCoins; ++i)
coins.add(rawCoins[i]);
Collections.sort(coins);
Collections.reverse(coins);
this.coins = coins;
}
public int leastNumCoins(int cents) {
int totalCoins = 0;
for (Integer val : coins) {
if (cents > 0) {
System.out.println(val);
int numCoins = cents / val;
cents -= numCoins * val;
totalCoins += numCoins;
}
} return totalCoins;
}
}
import junit.framework.TestCase;
public class ChangeTest extends TestCase {
Change maker;
protected void setUp() {
int[] coins = { 25, 10, 5, 1 };
maker = new Change(4, coins);
}
protected void tearDown() {
maker = null;
}
private int ncoins(int cents) {
return maker.leastNumCoins(cents);
}
public void testNoNegativeCoins() {
assertEquals(0, ncoins(-1));
}
public void testQuarter() {
assertEquals(4, ncoins(4 * 25));
}
public void testQuarterDime() {
assertEquals(2, ncoins(25 + 10));
}
public void testQuarterDimeNickel() {
assertEquals(3, ncoins(25 + 10 + 5));
}
public void testQuarterDimeNickelPenny() {
assertEquals(4, ncoins(25 + 10 + 5 + 1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment