Skip to content

Resistor Color Tolerance

Read the label of a resistor with one, four or five color bands: its resistance in ohms, kiloohms or megaohms, and the tolerance its last band marks.

Adapted from Exercism’s problem specification (MIT). Listed under Numbers & Math.

// FILE: resistor_color_tolerance.nomi
//# The label of a resistor with one, four or five color bands: its
//# resistance in the largest metric unit it reaches, and its tolerance.

/// A band color: the ten digit colors in value order, black 0 to white 9,
/// and the two that only mark a tolerance.
pub enum Color
    Black
    Brown
    Red
    Orange
    Yellow
    Green
    Blue
    Violet
    Grey
    White
    Gold
    Silver
end

/// The unit a resistance is written in, each a thousand times the one before.
pub enum Magnitude
    Ohms
    Kiloohms
    Megaohms
    Gigaohms
end

impl Display for Magnitude
    fn to_string(unit: Magnitude) -> String
        case unit
            .Ohms     -> "ohms"
            .Kiloohms -> "kiloohms"
            .Megaohms -> "megaohms"
            .Gigaohms -> "gigaohms"
        end
    end
end

/// A resistor's label: `33 ohms ±2%`. A one-band resistor has no tolerance.
pub struct Label
    value:     Decimal
    unit:      Magnitude
    tolerance: Maybe<Decimal>
end

impl Display for Label
    fn to_string(label: Label) -> String
        case label.tolerance
            Some(percent) -> "${label.value} ${label.unit} ±${percent}%"
            None          -> "${label.value} ${label.unit}"
        end
    end
end

/// The label `bands` give: a single black band, two digits, a multiplier
/// and a tolerance, or three digits, a multiplier and a tolerance. `None`
/// for any other count of bands, or a band whose color cannot stand there.
pub fn label(bands: List<Color>) -> Maybe<Label>
    case bands
        [.Black] ->
            Some({value: 0d, unit: .Ohms, tolerance: None})

        [first, second, multiplier, tolerance] ->
            make([first, second], multiplier, tolerance)

        [first, second, third, multiplier, tolerance] ->
            make([first, second, third], multiplier, tolerance)

        _ ->
            None
    end
end

/// The label of the digit bands `digits`, then `multiplier`, the number of
/// zeros after them, and `tolerance`.
fn make(digits: List<Color>, multiplier: Color, tolerance: Color) -> Maybe<Label>
    number =
        digits
        |> Iter.map(digit)
        |> Maybe.collect()?
        |> Int.from_digits()!

    zeros = digit(multiplier)?
    percent = tolerance_of(tolerance)?
    ohms = number * Int.pow(10, zeros)
    (value, unit) = in_largest_unit(ohms)
    Some({value:, unit:, tolerance: Some(percent)})
end

/// The units above ohms, largest first, with how many ohms each is.
once units: List<(PositiveInt, Magnitude)> = [
    (1_000_000_000, .Gigaohms),
    (1_000_000,     .Megaohms),
    (1000,          .Kiloohms),
]

/// `ohms` in the largest unit it reaches at least one of.
fn in_largest_unit(ohms: Int) -> (Decimal, Magnitude)
    case Iter.find(units, fn (size, _unit) -> ohms >= size)
        Some((size, unit)) -> (Int.to_decimal(ohms) / Int.to_decimal(size), unit)
        None               -> (Int.to_decimal(ohms), .Ohms)
    end
end

fn digit(color: Color) -> Maybe<NonNegativeInt>
    case color
        .Black           -> Some(0)
        .Brown           -> Some(1)
        .Red             -> Some(2)
        .Orange          -> Some(3)
        .Yellow          -> Some(4)
        .Green           -> Some(5)
        .Blue            -> Some(6)
        .Violet          -> Some(7)
        .Grey            -> Some(8)
        .White           -> Some(9)
        .Gold or .Silver -> None
    end
end

/// The tolerance in percent a band of `color` marks, if it marks one.
fn tolerance_of(color: Color) -> Maybe<Decimal>
    case color
        .Grey                                  -> Some(0.05d)
        .Violet                                -> Some(0.1d)
        .Blue                                  -> Some(0.25d)
        .Green                                 -> Some(0.5d)
        .Brown                                 -> Some(1d)
        .Red                                   -> Some(2d)
        .Gold                                  -> Some(5d)
        .Silver                                -> Some(10d)
        .Black or .Orange or .Yellow or .White -> None
    end
end

// FILE: resistor_color_tolerance_test.nomi
import resistor_color_tolerance.{self, Color, Label}

test "label decoder"
    cases: List<(String, List<Color>, Label)> = [
        (
            "Orange, orange, black and red",
            [.Orange, .Orange, .Black, .Red],
            {value: 33d, unit: .Ohms, tolerance: Some(2d)},
        ),
        (
            "Blue, gray, brown and violet",
            [.Blue, .Grey, .Brown, .Violet],
            {value: 680d, unit: .Ohms, tolerance: Some(0.1d)},
        ),
        (
            "Red, black, red and green",
            [.Red, .Black, .Red, .Green],
            {value: 2d, unit: .Kiloohms, tolerance: Some(0.5d)},
        ),
        (
            "Green, brownm orange and grey",
            [.Green, .Brown, .Orange, .Grey],
            {value: 51d, unit: .Kiloohms, tolerance: Some(0.05d)},
        ),
        ("Only one band", [.Black], {value: 0d, unit: .Ohms, tolerance: None}),
        (
            "Orange, orange, yellow, black and brown",
            [.Orange, .Orange, .Yellow, .Black, .Brown],
            {value: 334d, unit: .Ohms, tolerance: Some(1d)},
        ),
        (
            "Red, green, yellow, yellow and brown",
            [.Red, .Green, .Yellow, .Yellow, .Brown],
            {value: 2.54d, unit: .Megaohms, tolerance: Some(1d)},
        ),
        (
            "Blue, gray, white, brown and brown",
            [.Blue, .Grey, .White, .Brown, .Brown],
            {value: 6.89d, unit: .Kiloohms, tolerance: Some(1d)},
        ),
        (
            "Violet, orange, red and gray",
            [.Violet, .Orange, .Red, .Grey],
            {value: 7.3d, unit: .Kiloohms, tolerance: Some(0.05d)},
        ),
        (
            "Brown, red, orange, green and blue",
            [.Brown, .Red, .Orange, .Green, .Blue],
            {value: 12.3d, unit: .Megaohms, tolerance: Some(0.25d)},
        ),
        (
            "Brown, black, brown, yellow and violet",
            [.Brown, .Black, .Brown, .Yellow, .Violet],
            {value: 1.01d, unit: .Megaohms, tolerance: Some(0.1d)},
        ),
        (
            "Brown, black, red and red",
            [.Brown, .Black, .Red, .Red],
            {value: 1d, unit: .Kiloohms, tolerance: Some(2d)},
        ),
    ]

    subtests cases, (description, bands, expected), description
        assert resistor_color_tolerance.label(bands) == Some(expected)
    end
end

test "labels read as the description writes them"
    [
        ([Color.Orange, .Orange, .Black, .Green],  "33 ohms ±0.5%"),
        ([.Orange, .Orange, .Orange, .Grey],       "33 kiloohms ±0.05%"),
        ([.Orange, .Orange, .Blue, .Red],          "33 megaohms ±2%"),
        ([.Red, .Green, .Yellow, .Yellow, .Brown], "2.54 megaohms ±1%"),
        ([.Black],                                 "0 ohms"),
    ]
    |> subtests (bands, expected)
        assert Some(label) = resistor_color_tolerance.label(bands)
        assert "${label}" == expected
    end
end

test "bands that make no label"
    [
        ("no bands",                     []),
        ("one band that is not black",   [Color.Brown]),
        ("three bands",                  [.Brown, .Black, .Red]),
        ("a tolerance color as a digit", [.Gold, .Black, .Red, .Red]),
        ("a digit color as a tolerance", [.Brown, .Black, .Red, .Orange]),
    ]
    |> subtests (description, bands), description
        assert resistor_color_tolerance.label(bands) == None
    end
end
  • The colors are an enum, Color, with the ten digit colors in value order and the two tolerance-only colors, gold and silver. The canonical strings are the test table’s data, written as variants.
  • label returns Maybe<Label>, a struct of the value as a Decimal, the unit and the tolerance as a Maybe<Decimal> percent, None for the one-band resistor. The canonical answer is those three fields, so the table compares structs; Label’s Display writes the description’s text, 33 ohms ±2%, which a second table checks.
  • The bands are taken apart by one case over their count: a lone black band, two digits, or three digits, each then a multiplier and a tolerance. Any other count, or a color that cannot stand where it is (gold as a digit, orange as a tolerance), is None, which make passes up with ? at each band; Int.from_digits(...)! cannot fail there, since every digit is below ten. The canonical data has no such case, and the test file adds five, in a table of their own.
  • The value is a Decimal, since the canonical “2.54 megaohms” and “6.89 kiloohms” are exact decimals. The ohms are a whole number, divided with / by the largest unit they reach. The once table of units is annotated List<(PositiveInt, Magnitude)>, so each size is a PositiveInt and Int.to_decimal(size) a PositiveDecimal, which / takes as a divisor. Dividing by a power of ten is exact, and an exact quotient has no trailing zeros, so 680 stays 680 and 2540000 reads 2.54.
  • The units are an enum named Magnitude, as in resistor-color-trio: Unit is the prelude’s unit type and cannot be redeclared.
  • The canonical “Green, brownm orange and grey” case is reimplemented with a corrected tolerance; the table holds only the replacement, under the canonical description with its typo.