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

Bookstore.java 1.6KB

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