Guest User

Untitled

a guest
Dec 16th, 2015
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. package algorithms.Recursion;
  2.  
  3. public class RecursionMain {
  4. public static void main(String[] args){
  5. NumWaysMakeChange.waysMakeChangeDifferent(100);
  6. }
  7. }
  8.  
  9. package algorithms.Recursion;
  10.  
  11. import java.util.ArrayList;
  12.  
  13. public class NumWaysMakeChange {
  14. static int[] coinDenoms;
  15. public static void waysMakeChangeDifferent(int centsToChange){
  16. //Prepare data
  17. coinDenoms = new int[]{25,10,5,1};
  18. int startSum = 0;
  19. int startDenom = 0;
  20. int[] startCoins = new int[coinDenoms.length];
  21. ArrayList<int[]> cc = waysMakeChangeDifferentRecurse(centsToChange, startSum, startDenom, startCoins);
  22.  
  23. //Print result
  24. System.out.println("There are "+
  25. cc.size()+
  26. " different solutions." );
  27.  
  28. for (int[] c: cc){
  29. for (int coin:c){
  30. System.out.print(coin+" ");
  31. }
  32. System.out.println();
  33. }
  34. }
  35. private static ArrayList<int[]> waysMakeChangeDifferentRecurse(int centsToChange, int currentSum, int denomIndex, int[] currentCoins){
  36. ArrayList<int[]> ret = new ArrayList<int[]>();
  37. for (int i = denomIndex; i<coinDenoms.length;i++){
  38. //Iterate through coins of current size or smaller
  39. int newSum = currentSum+coinDenoms[i];
  40. if (newSum>centsToChange){
  41. //If we pass the amount
  42. continue;
  43. }
  44. if (newSum==centsToChange){
  45. //If we hit the right amount
  46. currentCoins[i]++;
  47. ret.add(currentCoins);
  48. return ret;
  49. }
  50. //If we're still approaching the right amount
  51. int[] tempCoins = currentCoins.clone();
  52. tempCoins[i]++;
  53. //Keep going deeper
  54. ArrayList<int[]> differentWays = waysMakeChangeDifferentRecurse(centsToChange, newSum, i, tempCoins);
  55. ret.addAll(differentWays);
  56. }
  57. return ret;
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment