lots of exercises in java... from https://github.com/exercism/java

BookStore.java 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.stream.Collectors;
  4. class BookStore {
  5. private static final int BOOK_PRICE = 8, MAX_GROUP_SIZE = 5;
  6. private static double[] DISCOUNT_TIERS = {0, 5, 10, 20, 25};
  7. double calculateBasketCost(final List<Integer> books) {
  8. return calculateBasketCost(books, 0);
  9. }
  10. private double calculateBasketCost(final List<Integer> books, final double priceSoFar) {
  11. if (books.size() == 0) {
  12. return priceSoFar;
  13. }
  14. List<Integer> availableBookNumbers = books.stream()
  15. .distinct()
  16. .collect(Collectors.toList());
  17. double minPrice = Double.MAX_VALUE;
  18. for (int i = 0; i < availableBookNumbers.size(); i++) {
  19. List<Integer> newGroupBooks = new ArrayList<>(availableBookNumbers.subList(0, i + 1));
  20. List<Integer> remainingBooks = new ArrayList<>(books);
  21. for (final Integer newGroupBook : newGroupBooks) {
  22. //noinspection UseBulkOperation - we want to remove _one_ of each book number, not _all_ of each book number.
  23. remainingBooks.remove(newGroupBook);
  24. }
  25. double price = calculateBasketCost(remainingBooks, priceSoFar + costOfGroupSize(newGroupBooks.size()));
  26. minPrice = Math.min(minPrice, price);
  27. }
  28. return minPrice;
  29. }
  30. private double costOfGroupSize(int groupSize) {
  31. if (groupSize < 1 || groupSize > MAX_GROUP_SIZE) {
  32. throw new IllegalStateException("Invalid group size : " + groupSize);
  33. }
  34. return BOOK_PRICE * groupSize * (100 - DISCOUNT_TIERS[groupSize - 1]) / 100;
  35. }
  36. }