Darts
Score a dart by how far from the centre of the target it lands.
Adapted from Exercism’s problem specification (MIT). Listed under Games & Simulation.
// FILE: darts.nomi
//# Scores a dart throw on a target of three circles.
/// The points a dart landing at `x`, `y` scores on a target centred on the
/// origin: 10 inside radius 1, 5 inside radius 5, 1 inside radius 10, and
/// nothing outside. A dart on a circle's edge counts as inside it.
pub fn score(x: Float, y: Float) -> Int
distance_squared = x * x + y * y
case
distance_squared <= 1.0 -> 10
distance_squared <= 25.0 -> 5
distance_squared <= 100.0 -> 1
_ -> 0
end
end
// FILE: darts_test.nomi
import darts
test "scores a toss"
[
("Missed target", (-9.0, 9.0), 0),
("On the outer circle", (0.0, 10.0), 1),
("On the middle circle", (-5.0, 0.0), 5),
("On the inner circle", (0.0, -1.0), 10),
("Exactly on center", (0.0, 0.0), 10),
("Near the center", (-0.1, -0.1), 10),
("Just within the inner circle", (0.7, 0.7), 10),
("Just outside the inner circle", (0.8, -0.8), 5),
("Just within the middle circle", (-3.5, 3.5), 5),
("Just outside the middle circle", (-3.6, -3.6), 1),
("Just within the outer circle", (-7.0, 7.0), 1),
("Just outside the outer circle", (7.1, -7.1), 0),
("Asymmetric position between the inner and middle circles", (0.5, -4.0), 5),
]
|> subtests (description, (x, y), expected), description
assert darts.score(x, y) == expected
end
endok scores a toss (13 cases)
test result: ok. 13 passed, 0 failed
How it’s written
Section titled “How it’s written”- The distance is compared squared, against 1, 25 and 100, so no square root is needed and a dart exactly on a circle (
0, 10) scores as inside it with no rounding. - The bands are the arms of a
casewith no subject, one condition each, checked from the inside out. Anif/else ifladder was the other form; the arms line up the radii and their points. scoretakes twoFloats and returns anInt. The canonical inputs that are whole numbers are written9.0in the tests, since anIntliteral is not aFloat.- The 13 cases are one
subteststable whose middle column is the(x, y)point.