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

Add pop-count exercise #240

Merged
merged 2 commits into from
Nov 1, 2023
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
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,14 @@
"math"
]
},
{
"slug": "pop-count",
"name": "Pop Count",
"uuid": "76d154fe-a39c-4d0e-a43a-f18e36388c83",
"practices": [],
"prerequisites": [],
"difficulty": 2
},
{
"slug": "phone-number",
"name": "Phone Number",
Expand Down
8 changes: 8 additions & 0 deletions exercises/practice/pop-count/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Instructions

Your task is to count the number of 1 bits in the binary representation of a number.

## Restrictions

Keep your hands off that bit-count functionality provided by your standard library!
Solve this one yourself using other basic tools instead.
47 changes: 47 additions & 0 deletions exercises/practice/pop-count/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Introduction

Your friend Eliud inherited a farm from her grandma Tigist.
Her granny was an inventor and had a tendency to build things in an overly complicated manner.
The chicken coop has a digital display showing an encoded number representing the positions of all eggs that could be picked up.

Eliud is asking you to write a program that shows the actual number of eggs in the coop.

The position information encoding is calculated as follows:

1. Scan the potential egg-laying spots and mark down a `1` for an existing egg or a `0` for an empty spot.
2. Convert the number from binary to decimal.
3. Show the result on the display.

Example 1:

```text
Chicken Coop:
_ _ _ _ _ _ _
|E| |E|E| | |E|

Resulting Binary:
1 0 1 1 0 0 1

Decimal number on the display:
89

Actual eggs in the coop:
4
```

Example 2:

```text
Chicken Coop:
_ _ _ _ _ _ _ _
| | | |E| | | | |

Resulting Binary:
0 0 0 1 0 0 0 0

Decimal number on the display:
16

Actual eggs in the coop:
1
```
19 changes: 19 additions & 0 deletions exercises/practice/pop-count/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"BNAndras"
],
"files": {
"solution": [
"pop-count.sml"
],
"test": [
"test.sml"
],
"example": [
".meta/example.sml"
]
},
"blurb": "Count the 1 bits in a number",
"source": "Christian Willner, Eric Willigers",
"source_url": "https://forum.exercism.org/t/new-exercise-suggestion-pop-count/7632/5"
}
9 changes: 9 additions & 0 deletions exercises/practice/pop-count/.meta/example.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
fun eggCount (number: int) : int =
let
fun recurse n acc =
if n = 0 then acc
else if (n mod 2) = 0 then recurse (n div 2) (acc)
else recurse (n div 2) (acc + 1)
in
recurse number 0
end
22 changes: 22 additions & 0 deletions exercises/practice/pop-count/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# 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.

[559e789d-07d1-4422-9004-3b699f83bca3]
description = "0 eggs"

[97223282-f71e-490c-92f0-b3ec9e275aba]
description = "1 egg"

[1f8fd18f-26e9-4144-9a0e-57cdfc4f4ff5]
description = "4 eggs"

[0c18be92-a498-4ef2-bcbb-28ac4b06cb81]
description = "13 eggs"
2 changes: 2 additions & 0 deletions exercises/practice/pop-count/pop-count.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
fun eggCount (number: int): int =
raise Fail "'eggCount' is not implemented"
22 changes: 22 additions & 0 deletions exercises/practice/pop-count/test.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use "testlib.sml";
use "pop-count.sml";

infixr |>
fun x |> f = f x

val testsuite =
describe "pop-count" [
test "0 eggs"
(fn _ => eggCount 0 |> Expect.equalTo 0),

test "1 egg"
(fn _ => eggCount 16 |> Expect.equalTo 1),

test "4 eggs"
(fn _ => eggCount 89 |> Expect.equalTo 4),

test "13 eggs"
(fn _ => eggCount 2000000000 |> Expect.equalTo 13)
]

val _ = Test.run testsuite
160 changes: 160 additions & 0 deletions exercises/practice/pop-count/testlib.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
structure Expect =
struct
datatype expectation = Pass | Fail of string * string

local
fun failEq b a =
Fail ("Expected: " ^ b, "Got: " ^ a)

fun failExn b a =
Fail ("Expected: " ^ b, "Raised: " ^ a)

fun exnName (e: exn): string = General.exnName e
in
fun truthy a =
if a
then Pass
else failEq "true" "false"

fun falsy a =
if a
then failEq "false" "true"
else Pass

fun equalTo b a =
if a = b
then Pass
else failEq (PolyML.makestring b) (PolyML.makestring a)

fun nearTo delta b a =
if Real.abs (a - b) <= delta * Real.abs a orelse
Real.abs (a - b) <= delta * Real.abs b
then Pass
else failEq (Real.toString b ^ " +/- " ^ Real.toString delta) (Real.toString a)

fun anyError f =
(
f ();
failExn "an exception" "Nothing"
) handle _ => Pass

fun error e f =
(
f ();
failExn (exnName e) "Nothing"
) handle e' => if exnMessage e' = exnMessage e
then Pass
else failExn (exnMessage e) (exnMessage e')
end
end

structure TermColor =
struct
datatype color = Red | Green | Yellow | Normal

fun f Red = "\027[31m"
| f Green = "\027[32m"
| f Yellow = "\027[33m"
| f Normal = "\027[0m"

fun colorize color s = (f color) ^ s ^ (f Normal)

val redit = colorize Red

val greenit = colorize Green

val yellowit = colorize Yellow
end

structure Test =
struct
datatype testnode = TestGroup of string * testnode list
| Test of string * (unit -> Expect.expectation)

local
datatype evaluation = Success of string
| Failure of string * string * string
| Error of string * string

fun indent n s = (implode (List.tabulate (n, fn _ => #" "))) ^ s

fun fmt indentlvl ev =
let
val check = TermColor.greenit "\226\156\148 " (* ✔ *)
val cross = TermColor.redit "\226\156\150 " (* ✖ *)
val indentlvl = indentlvl * 2
in
case ev of
Success descr => indent indentlvl (check ^ descr)
| Failure (descr, exp, got) =>
String.concatWith "\n" [indent indentlvl (cross ^ descr),
indent (indentlvl + 2) exp,
indent (indentlvl + 2) got]
| Error (descr, reason) =>
String.concatWith "\n" [indent indentlvl (cross ^ descr),
indent (indentlvl + 2) (TermColor.redit reason)]
end

fun eval (TestGroup _) = raise Fail "Only a 'Test' can be evaluated"
| eval (Test (descr, thunk)) =
(
case thunk () of
Expect.Pass => ((1, 0, 0), Success descr)
| Expect.Fail (s, s') => ((0, 1, 0), Failure (descr, s, s'))
)
handle e => ((0, 0, 1), Error (descr, "Unexpected error: " ^ exnMessage e))

fun flatten depth testnode =
let
fun sum (x, y, z) (a, b, c) = (x + a, y + b, z + c)

fun aux (t, (counter, acc)) =
let
val (counter', texts) = flatten (depth + 1) t
in
(sum counter' counter, texts :: acc)
end
in
case testnode of
TestGroup (descr, ts) =>
let
val (counter, texts) = foldr aux ((0, 0, 0), []) ts
in
(counter, (indent (depth * 2) descr) :: List.concat texts)
end
| Test _ =>
let
val (counter, evaluation) = eval testnode
in
(counter, [fmt depth evaluation])
end
end

fun println s = print (s ^ "\n")
in
fun run suite =
let
val ((succeeded, failed, errored), texts) = flatten 0 suite

val summary = String.concatWith ", " [
TermColor.greenit ((Int.toString succeeded) ^ " passed"),
TermColor.redit ((Int.toString failed) ^ " failed"),
TermColor.redit ((Int.toString errored) ^ " errored"),
(Int.toString (succeeded + failed + errored)) ^ " total"
]

val status = if failed = 0 andalso errored = 0
then OS.Process.success
else OS.Process.failure

in
List.app println texts;
println "";
println ("Tests: " ^ summary);
OS.Process.exit status
end
end
end

fun describe description tests = Test.TestGroup (description, tests)
fun test description thunk = Test.Test (description, thunk)