Skip to content

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
end
  • 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 case with no subject, one condition each, checked from the inside out. An if/else if ladder was the other form; the arms line up the radii and their points.
  • score takes two Floats and returns an Int. The canonical inputs that are whole numbers are written 9.0 in the tests, since an Int literal is not a Float.
  • The 13 cases are one subtests table whose middle column is the (x, y) point.