Skip to content

[#766] New practice exercise circular-buffer #775

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

Merged
merged 7 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
27 changes: 27 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2550,6 +2550,33 @@
"list-comprehensions"
],
"difficulty": 8
},
{
"slug": "circular-buffer",
"name": "Circular Buffer",
"uuid": "535d64c9-95f7-4f59-b7b6-d459337b82b0",
"prerequisites": [
"atoms",
"tuples",
"lists",
"structs",
"enum",
"agent",
"processes",
"pids",
"case",
"cond",
"if",
"multiple-clause-functions",
"pattern-matching",
"guards",
"errors"
],
"practices": [
"processes",
Copy link
Member

Choose a reason for hiding this comment

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

Woohoo, we needed more exercises that practice processes 💜

"errors"
Copy link
Member

Choose a reason for hiding this comment

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

@neenjaw Do you remember how we defined practicing/requiring "errors"? Is it about the ok/error-tuple pattern, or is it about using raise (exceptions is definitely about defining custom ones)?

Copy link
Contributor

Choose a reason for hiding this comment

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

I think it is implemented to exercise raise

Copy link
Contributor

Choose a reason for hiding this comment

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

I'm not opposed to this addition though, it is an accepted way of handling errors

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

A circular buffer, cyclic buffer or ring buffer is a data structure that
uses a single, fixed-size buffer as if it were connected end-to-end.

A circular buffer first starts empty and of some predefined length. For
example, this is a 7-element buffer:
<!-- prettier-ignore -->
[ ][ ][ ][ ][ ][ ][ ]

Assume that a 1 is written into the middle of the buffer (exact starting
location does not matter in a circular buffer):
<!-- prettier-ignore -->
[ ][ ][ ][1][ ][ ][ ]

Then assume that two more elements are added — 2 & 3 — which get
appended after the 1:
<!-- prettier-ignore -->
[ ][ ][ ][1][2][3][ ]

If two elements are then removed from the buffer, the oldest values
inside the buffer are removed. The two elements removed, in this case,
are 1 & 2, leaving the buffer with just a 3:
<!-- prettier-ignore -->
[ ][ ][ ][ ][ ][3][ ]

If the buffer has 7 elements then it is completely full:
<!-- prettier-ignore -->
[5][6][7][8][9][3][4]

When the buffer is full an error will be raised, alerting the client
that further writes are blocked until a slot becomes free.

When the buffer is full, the client can opt to overwrite the oldest
data with a forced write. In this case, two more elements — A & B —
are added and they overwrite the 3 & 4:
<!-- prettier-ignore -->
[5][6][7][8][9][A][B]

3 & 4 have been replaced by A & B making 5 now the oldest data in the
buffer. Finally, if two elements are removed then what would be
returned is 5 & 6 yielding the buffer:
<!-- prettier-ignore -->
[ ][ ][7][8][9][A][B]

Because there is space available, if the client again uses overwrite
to store C & D then the space where 5 & 6 were stored previously will
be used not the location of 7 & 8. 7 is still the oldest element and
the buffer is once again full.
<!-- prettier-ignore -->
[C][D][7][8][9][A][B]
4 changes: 4 additions & 0 deletions exercises/practice/circular-buffer/.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}"]
]
20 changes: 20 additions & 0 deletions exercises/practice/circular-buffer/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"authors": ["jiegillet"],
"contributors": [
"angelikatyborska"
],
"files": {
"example": [
".meta/example.ex"
],
"solution": [
"lib/circular_buffer.ex"
],
"test": [
"test/circular_buffer_test.exs"
]
},
"blurb": "A data structure that uses a single, fixed-size buffer as if it were connected end-to-end.",
"source": "Wikipedia",
"source_url": "http://en.wikipedia.org/wiki/Circular_buffer"
}
110 changes: 110 additions & 0 deletions exercises/practice/circular-buffer/.meta/example.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
defmodule CircularBuffer do
use GenServer

@moduledoc """
An API to a stateful process that fills and empties a circular buffer
"""

# CLIENT API

@doc """
Create a new buffer of a given capacity
"""
@spec new(capacity :: integer) :: {:ok, pid}
def new(capacity) do
GenServer.start_link(__MODULE__, capacity, [])
end

@doc """
Read the oldest entry in the buffer, fail if it is empty
"""
@spec read(buffer :: pid) :: {:ok, any} | {:error, atom}
def read(buffer) do
GenServer.call(buffer, :read)
end

@doc """
Write a new item in the buffer, fail if is full
"""
@spec write(buffer :: pid, item :: any) :: :ok | {:error, atom}
def write(buffer, item) do
GenServer.call(buffer, {:write, item})
end

@doc """
Write an item in the buffer, overwrite the oldest entry if it is full
"""
@spec overwrite(buffer :: pid, item :: any) :: :ok
def overwrite(buffer, item) do
GenServer.cast(buffer, {:overwrite, item})
end

@doc """
Clear the buffer
"""
@spec clear(buffer :: pid) :: :ok
def clear(buffer) do
GenServer.cast(buffer, :clear)
end

# DATA STRUCTURE
# Essentially a deque made out of two lists, one for new input (write, overwrite)
# and one for output (read), and keeping track of the size and capacity.

defstruct [:capacity, size: 0, input: [], output: []]

def new_buffer(capacity), do: {:ok, %CircularBuffer{capacity: capacity}}

def read_buffer(%CircularBuffer{size: 0} = buffer), do: {{:error, :empty}, buffer}

def read_buffer(%CircularBuffer{size: size, output: [out | output]} = buffer),
do: {{:ok, out}, %{buffer | size: size - 1, output: output}}

def read_buffer(%CircularBuffer{input: input} = buffer),
do: read_buffer(%{buffer | input: [], output: Enum.reverse(input)})

def write_buffer(%CircularBuffer{size: capacity, capacity: capacity} = buffer, _item),
do: {{:error, :full}, buffer}

def write_buffer(%CircularBuffer{size: size, input: input} = buffer, item),
do: {:ok, %{buffer | size: size + 1, input: [item | input]}}

def overwrite_buffer(%CircularBuffer{size: capacity, capacity: capacity} = buffer, item) do
{_, smaller_buffer} = read_buffer(buffer)
write_buffer(smaller_buffer, item)
end

def overwrite_buffer(buffer, item), do: write_buffer(buffer, item)

def clear_buffer(%CircularBuffer{capacity: capacity}), do: %CircularBuffer{capacity: capacity}

@impl true
def init(capacity) do
new_buffer(capacity)
end

# SERVER API

@impl true
def handle_call(:read, _from, buffer) do
{reply, buffer} = read_buffer(buffer)
{:reply, reply, buffer}
end

@impl true
def handle_call({:write, item}, _from, buffer) do
{reply, buffer} = write_buffer(buffer, item)
{:reply, reply, buffer}
end

@impl true
def handle_cast({:overwrite, item}, buffer) do
{_reply, buffer} = overwrite_buffer(buffer, item)
{:noreply, buffer}
end

@impl true
def handle_cast(:clear, buffer) do
{:noreply, clear_buffer(buffer)}
end
end
51 changes: 51 additions & 0 deletions exercises/practice/circular-buffer/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# 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.
[28268ed4-4ff3-45f3-820e-895b44d53dfa]
description = "reading empty buffer should fail"

[2e6db04a-58a1-425d-ade8-ac30b5f318f3]
description = "can read an item just written"

[90741fe8-a448-45ce-be2b-de009a24c144]
description = "each item may only be read once"

[be0e62d5-da9c-47a8-b037-5db21827baa7]
description = "items are read in the order they are written"

[2af22046-3e44-4235-bfe6-05ba60439d38]
description = "full buffer can't be written to"

[547d192c-bbf0-4369-b8fa-fc37e71f2393]
description = "a read frees up capacity for another write"

[04a56659-3a81-4113-816b-6ecb659b4471]
description = "read position is maintained even across multiple writes"

[60c3a19a-81a7-43d7-bb0a-f07242b1111f]
description = "items cleared out of buffer can't be read"

[45f3ae89-3470-49f3-b50e-362e4b330a59]
description = "clear frees up capacity for another write"

[e1ac5170-a026-4725-bfbe-0cf332eddecd]
description = "clear does nothing on empty buffer"

[9c2d4f26-3ec7-453f-a895-7e7ff8ae7b5b]
description = "overwrite acts like write on non-full buffer"

[880f916b-5039-475c-bd5c-83463c36a147]
description = "overwrite replaces the oldest item on full buffer"

[bfecab5b-aca1-4fab-a2b0-cd4af2b053c3]
description = "overwrite replaces the oldest item remaining in buffer following a read"

[9cebe63a-c405-437b-8b62-e3fdc1ecec5a]
description = "initial clear does not affect wrapping around"
40 changes: 40 additions & 0 deletions exercises/practice/circular-buffer/lib/circular_buffer.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
defmodule CircularBuffer do
@moduledoc """
An API to a stateful process that fills and empties a circular buffer
"""

@doc """
Create a new buffer of a given capacity
"""
@spec new(capacity :: integer) :: {:ok, pid}
def new(capacity) do
end

@doc """
Read the oldest entry in the buffer, fail if it is empty
"""
@spec read(buffer :: pid) :: {:ok, any} | {:error, atom}
def read(buffer) do
end

@doc """
Write a new item in the buffer, fail if is full
"""
@spec write(buffer :: pid, item :: any) :: :ok | {:error, atom}
def write(buffer, item) do
end

@doc """
Write an item in the buffer, overwrite the oldest entry if it is full
"""
@spec overwrite(buffer :: pid, item :: any) :: :ok
def overwrite(buffer, item) do
end

@doc """
Clear the buffer
"""
@spec clear(buffer :: pid) :: :ok
def clear(buffer) do
end
end
28 changes: 28 additions & 0 deletions exercises/practice/circular-buffer/mix.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
defmodule CircularBuffer.MixProject do
use Mix.Project

def project do
[
app: :circular_buffer,
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