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 resistor-color exercise #273

Merged
merged 2 commits into from
Jan 19, 2024
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 @@ -357,6 +357,14 @@
"difficulty": 1,
"topics": []
},
{
"slug": "resistor-color",
"name": "Resistor Color",
"uuid": "85f16b58-019f-44f7-bb33-b2903886f199",
"practices": [],
"prerequisites": [],
"difficulty": 1
},
{
"slug": "rna-transcription",
"name": "RNA Transcription",
Expand Down
39 changes: 39 additions & 0 deletions exercises/practice/resistor-color/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Instructions

If you want to build something using a Raspberry Pi, you'll probably use _resistors_.
For this exercise, you need to know two things about them:

- Each resistor has a resistance value.
- Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to read.

To get around this problem, manufacturers print color-coded bands onto the resistors to denote their resistance values.
Each band has a position and a numeric value.

The first 2 bands of a resistor have a simple encoding scheme: each color maps to a single number.

In this exercise you are going to create a helpful program so that you don't have to remember the values of the bands.

These colors are encoded as follows:

- Black: 0
- Brown: 1
- Red: 2
- Orange: 3
- Yellow: 4
- Green: 5
- Blue: 6
- Violet: 7
- Grey: 8
- White: 9

The goal of this exercise is to create a way:

- to look up the numerical value associated with a particular color band
- to list the different band colors

Mnemonics map the colors to the numbers, that, when stored as an array, happen to map to their index in the array:
Better Be Right Or Your Great Big Values Go Wrong.

More information on the color encoding of resistors can be found in the [Electronic color code Wikipedia article][e-color-code].

[e-color-code]: https://en.wikipedia.org/wiki/Electronic_color_code
19 changes: 19 additions & 0 deletions exercises/practice/resistor-color/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"keiravillekode"
],
"files": {
"solution": [
"resistor-color.sml"
],
"test": [
"test.sml"
],
"example": [
".meta/example.sml"
]
},
"blurb": "Convert a resistor band's color to its numeric representation.",
"source": "Maud de Vries, Erik Schierboom",
"source_url": "https://github.com/exercism/problem-specifications/issues/1458"
}
14 changes: 14 additions & 0 deletions exercises/practice/resistor-color/.meta/example.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
val colors =
["black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white"]

fun colorCode (color: string) =
let
fun recurse (l: string list, index: int): int =
case l of
nil => raise Fail "invalid color"
| first :: rest =>
if first = color then index
else recurse (rest, index + 1)
in
recurse (colors, 0)
end
22 changes: 22 additions & 0 deletions exercises/practice/resistor-color/.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.

[49eb31c5-10a8-4180-9f7f-fea632ab87ef]
description = "Color codes -> Black"

[0a4df94b-92da-4579-a907-65040ce0b3fc]
description = "Color codes -> White"

[5f81608d-f36f-4190-8084-f45116b6f380]
description = "Color codes -> Orange"

[581d68fa-f968-4be2-9f9d-880f2fb73cf7]
description = "Colors"
5 changes: 5 additions & 0 deletions exercises/practice/resistor-color/resistor-color.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
fun colorCode color =
raise Fail "'colorCode' is not implemented"

val colors: string list =
nil
30 changes: 30 additions & 0 deletions exercises/practice/resistor-color/test.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
(* version 1.0.0 *)

use "testlib.sml";
use "resistor-color.sml";

infixr |>
fun x |> f = f x

val testsuite =
describe "resistor-color" [
describe "Color codes" [
test "Black"
(fn _ => colorCode "black" |> Expect.equalTo 0),

test "White"
(fn _ => colorCode "white" |> Expect.equalTo 9),

test "Orange"
(fn _ => colorCode "orange" |> Expect.equalTo 3)
],

test "Colors"
(fn _ => let
val expected = ["black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white"]
in
colors |> Expect.equalTo expected
end)
]

val _ = Test.run testsuite
160 changes: 160 additions & 0 deletions exercises/practice/resistor-color/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)