Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import static org.junit.Assert.assertEquals;
  2. import java.util.List;
  3. import java.util.stream.IntStream;
  4.  
  5. public class ShoppingBudget {
  6.  
  7. public static void main(String[] args) {
  8. ShoppingBudget sb = new ShoppingBudget();
  9. assertEquals(40, sb.budgetShopping(50, List.of(20, 19), List.of(24, 20)));
  10. assertEquals(20, sb.budgetShopping(4, List.of(10), List.of(2)));
  11. assertEquals(0, sb.budgetShopping(1, List.of(10), List.of(2)));
  12. assertEquals(41, sb.budgetShopping(50, List.of(20, 1), List.of(24, 2)));
  13. }
  14.  
  15. private void permute(int start, int moneyAvailable, int[] inputIndices,
  16. List<Integer> budgetQuantities, List<Integer> budgetCosts, MaxQuantity maxQuantity) {
  17. if (start == inputIndices.length) { // base case
  18.  
  19. int possibleMax = findSolution(inputIndices, moneyAvailable, budgetQuantities, budgetCosts);
  20.  
  21. maxQuantity.value = Math.max(maxQuantity.value, possibleMax);
  22.  
  23. return;
  24. }
  25. for (int i = start; i < inputIndices.length; i++) {
  26. // swapping
  27. int temp = inputIndices[i];
  28. inputIndices[i] = inputIndices[start];
  29. inputIndices[start] = temp;
  30. // swap(input[i], input[start]);
  31.  
  32. permute(start + 1, moneyAvailable, inputIndices, budgetQuantities, budgetCosts, maxQuantity);
  33. // swap(input[i],input[start]);
  34.  
  35. int temp2 = inputIndices[i];
  36. inputIndices[i] = inputIndices[start];
  37. inputIndices[start] = temp2;
  38. }
  39. }
  40.  
  41. private int findSolution(int[] inputIndices, int moneyAvailable,
  42. List<Integer> budgetQuantities, List<Integer> budgetCosts) {
  43. int remaining = moneyAvailable;
  44. int counter = 0;
  45.  
  46. for (int index : inputIndices) {
  47. if (remaining == 0) {
  48. break;
  49. }
  50.  
  51. int quantity = budgetQuantities.get(index);
  52. int cost = budgetCosts.get(index);
  53.  
  54. if (cost <= remaining) {
  55. int howManyToBuy = remaining / cost;
  56. counter += howManyToBuy * quantity;
  57. remaining -= (howManyToBuy * cost);
  58. }
  59. }
  60.  
  61. return counter;
  62. }
  63.  
  64. private int budgetShopping(int n, List<Integer> budgetQuantities,
  65. List<Integer> budgetCosts) {
  66. int[] inputIndices = IntStream.rangeClosed(0, budgetQuantities.size() - 1).toArray();
  67. MaxQuantity maxQuantity = new MaxQuantity();
  68. maxQuantity.value = Integer.MIN_VALUE;
  69. permute(0, n, inputIndices, budgetQuantities, budgetCosts, maxQuantity);
  70.  
  71. return maxQuantity.value;
  72. }
  73. }
  74.  
  75. class MaxQuantity {
  76. int value;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement