Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#764] New practice exercise book-store #778

Merged
merged 5 commits into from
Jun 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2491,6 +2491,27 @@
"strings"
],
"difficulty": 5
},
{
"slug": "book-store",
"name": "Book Store",
"uuid": "d6d9687c-8bf0-482e-8309-4f3d706ba753",
"prerequisites": [
"lists",
"pattern-matching",
"guards",
angelikatyborska marked this conversation as resolved.
Show resolved Hide resolved
"multiple-clause-functions",
"enum",
"list-comprehensions",
"maps",
"pipe-operator",
"ranges",
"recursion"
],
"practices": [
"list-comprehensions"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If nothing fits or everything that fits already has 10 exercises, we could also leave this empty.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or we can also leave lists comprehensions and see if people complain :)

],
"difficulty": 8
}
],
"foregone": [
Expand Down
68 changes: 68 additions & 0 deletions exercises/practice/book-store/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Description

To try and encourage more sales of different books from a popular 5 book
series, a bookshop has decided to offer discounts on multiple book purchases.

One copy of any of the five books costs $8.

If, however, you buy two different books, you get a 5%
discount on those two books.

If you buy 3 different books, you get a 10% discount.

If you buy 4 different books, you get a 20% discount.

If you buy all 5, you get a 25% discount.

Note: that if you buy four books, of which 3 are
different titles, you get a 10% discount on the 3 that
form part of a set, but the fourth book still costs $8.

Your mission is to write a piece of code to calculate the
price of any conceivable shopping basket (containing only
books of the same series), giving as big a discount as
possible.

For example, how much does this basket of books cost?

- 2 copies of the first book
- 2 copies of the second book
- 2 copies of the third book
- 1 copy of the fourth book
- 1 copy of the fifth book

One way of grouping these 8 books is:

- 1 group of 5 --> 25% discount (1st,2nd,3rd,4th,5th)
- +1 group of 3 --> 10% discount (1st,2nd,3rd)

This would give a total of:

- 5 books at a 25% discount
- +3 books at a 10% discount

Resulting in:

- 5 x (8 - 2.00) == 5 x 6.00 == $30.00
- +3 x (8 - 0.80) == 3 x 7.20 == $21.60

For a total of $51.60

However, a different way to group these 8 books is:

- 1 group of 4 books --> 20% discount (1st,2nd,3rd,4th)
- +1 group of 4 books --> 20% discount (1st,2nd,3rd,5th)

This would give a total of:

- 4 books at a 20% discount
- +4 books at a 20% discount

Resulting in:

- 4 x (8 - 1.60) == 4 x 6.40 == $25.60
- +4 x (8 - 1.60) == 4 x 6.40 == $25.60

For a total of $51.20

And $51.20 is the price with the biggest discount.
4 changes: 4 additions & 0 deletions exercises/practice/book-store/.formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
18 changes: 18 additions & 0 deletions exercises/practice/book-store/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"authors": ["jiegillet"],
"contributors": [],
"files": {
"example": [
".meta/example.ex"
],
"solution": [
"lib/book_store.ex"
],
"test": [
"test/book_store_test.exs"
]
},
"blurb": "To try and encourage more sales of different books from a popular 5 book series, a bookshop has decided to offer discounts of multiple-book purchases.",
"source": "Inspired by the harry potter kata from Cyber-Dojo.",
"source_url": "http://cyber-dojo.org"
}
67 changes: 67 additions & 0 deletions exercises/practice/book-store/.meta/example.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
defmodule BookStore do
use Agent
@type book :: integer

@base_price 800
@discount %{
1 => @base_price,
2 => div(@base_price * 95, 100),
3 => div(@base_price * 90, 100),
4 => div(@base_price * 80, 100),
5 => div(@base_price * 75, 100)
}

@doc """
Calculate lowest price (in cents) for a shopping basket containing books.
"""
@spec total(basket :: [book]) :: integer
def total(basket) do
# We use an Agent to memoize the discounts
{:ok, _pid} = Agent.start_link(fn -> %{} end, name: :discount)

basket
|> frequencies
|> Enum.sort()
|> discounts()
|> Enum.min()
end

def frequencies(list) do
list
|> Enum.map(&%{&1 => 1})
|> Enum.reduce(%{}, &Map.merge(&1, &2, fn _item, a, b -> a + b end))
|> Map.values()
end

def discounts([]), do: [0]
def discounts([n]), do: [n * @base_price]

def discounts(frequencies) do
cached = Agent.get(:discount, &Map.get(&1, frequencies))

if cached do
cached
else
discount =
for num_books <- 2..5,
{picked, left} <- pick_n_distinct_from(num_books, frequencies),
remove_picked = picked |> Enum.map(&(&1 - 1)) |> Enum.reject(&(&1 == 0)),
costs <- discounts(Enum.sort(remove_picked ++ left)),
do: costs + num_books * @discount[num_books]

Agent.update(:discount, &Map.put(&1, frequencies, discount))
discount
end
end

def pick_n_distinct_from(n, list) when length(list) < n, do: %{}
def pick_n_distinct_from(0, list), do: %{[] => list}
def pick_n_distinct_from(n, list) when length(list) == n, do: %{list => []}

def pick_n_distinct_from(n, list) do
for pick <- Enum.uniq(list),
{picked, left} <- pick_n_distinct_from(n - 1, list -- [pick]),
into: %{},
do: {Enum.sort([pick | picked]), left}
end
end
54 changes: 54 additions & 0 deletions exercises/practice/book-store/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.
[17146bd5-2e80-4557-ab4c-05632b6b0d01]
description = "Only a single book"

[cc2de9ac-ff2a-4efd-b7c7-bfe0f43271ce]
description = "Two of the same book"

[5a86eac0-45d2-46aa-bbf0-266b94393a1a]
description = "Empty basket"

[158bd19a-3db4-4468-ae85-e0638a688990]
description = "Two different books"

[f3833f6b-9332-4a1f-ad98-6c3f8e30e163]
description = "Three different books"

[1951a1db-2fb6-4cd1-a69a-f691b6dd30a2]
description = "Four different books"

[d70f6682-3019-4c3f-aede-83c6a8c647a3]
description = "Five different books"

[78cacb57-911a-45f1-be52-2a5bd428c634]
description = "Two groups of four is cheaper than group of five plus group of three"

[f808b5a4-e01f-4c0d-881f-f7b90d9739da]
description = "Two groups of four is cheaper than groups of five and three"

[fe96401c-5268-4be2-9d9e-19b76478007c]
description = "Group of four plus group of two is cheaper than two groups of three"

[68ea9b78-10ad-420e-a766-836a501d3633]
description = "Two each of first 4 books and 1 copy each of rest"

[c0a779d5-a40c-47ae-9828-a340e936b866]
description = "Two copies of each book"

[18fd86fe-08f1-4b68-969b-392b8af20513]
description = "Three copies of first book and 2 each of remaining"

[0b19a24d-e4cf-4ec8-9db2-8899a41af0da]
description = "Three each of first 2 books and 2 each of remaining books"

[bb376344-4fb2-49ab-ab85-e38d8354a58d]
description = "Four groups of four are cheaper than two groups each of five and three"
11 changes: 11 additions & 0 deletions exercises/practice/book-store/lib/book_store.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
defmodule BookStore do
@typedoc "A book is represented by its number in the 5-book series"
@type book :: 1 | 2 | 3 | 4 | 5

@doc """
Calculate lowest price (in cents) for a shopping basket containing books.
"""
@spec total(basket :: [book]) :: integer
def total(basket) do
end
end
28 changes: 28 additions & 0 deletions exercises/practice/book-store/mix.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
defmodule BookStore.MixProject do
use Mix.Project

def project do
[
app: :book_store,
version: "0.1.0",
# elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end

# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end

# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
Loading