Skip to content

Tournament

Tally the results of a small football competition into a league table, ordered by points and then by name.

Adapted from Exercism’s problem specification (MIT). Listed under Collections & Algorithms.

// FILE: tournament.nomi
//# Tallies a small football competition into a league table.

import std::reverse.Reverse

/// Why the results could not be tallied.
pub enum Error
    /// A row is not `home;away;outcome` with an outcome of `win`, `draw` or
    /// `loss`.
    InvalidRow String
end

/// How a match ended for one of its teams.
enum Outcome
    Win
    Draw
    Loss
end

impl Outcome
    fn parse(word: String) -> Maybe<Outcome>
        case word
            "win"  -> Some(.Win)
            "draw" -> Some(.Draw)
            "loss" -> Some(.Loss)
            _      -> None
        end
    end

    /// How the match ended for the other team.
    fn reverse(outcome: Outcome) -> Outcome
        case outcome
            .Win  -> .Loss
            .Draw -> .Draw
            .Loss -> .Win
        end
    end
end

/// One team's line of the table.
struct Standing
    team:  String
    won:   Int
    drawn: Int
    lost:  Int
end

impl Standing
    fn played(standing: Standing) -> Int
        standing.won + standing.drawn + standing.lost
    end

    fn points(standing: Standing) -> Int
        3 * standing.won + standing.drawn
    end
end

/// The league table for `rows`, one match per row written
/// `home;away;outcome`, where the outcome is the home team's. Teams are
/// ordered by points, most first, and then by name.
pub fn tally(rows: List<String>) -> Result<List<String>, Error>
    results =
        rows
        |> Iter.map(parse_row)
        |> Result.collect()?
        |> Iter.flatten()

    standings =
        results
        |> Iter.group_by(fn (team, _outcome) -> team)
        |> Iter.map(fn (team, rows) ->
            standing(team, Iter.map(rows, fn (_team, outcome) -> outcome))
        end)
        |> Iter.sort_by(fn s -> (Reverse.of(Standing.points(s)), s.team))

    table = Iter.map(standings, fn s ->
        numbers = [Standing.played(s), s.won, s.drawn, s.lost, Standing.points(s)]
        line(s.team, Iter.map(numbers, Int.to_string))
    end)

    Ok([line("Team", ["MP", "W", "D", "L", "P"]), ..table])
end

/// The outcome of the match in `row` for each of its two teams.
fn parse_row(row: String) -> Result<List<(String, Outcome)>, Error>
    [home, away, word] = String.split(row, ";") else return Err(.InvalidRow(row))

    Some(outcome) = Outcome.parse(word) else return Err(.InvalidRow(row))

    Ok([(home, outcome), (away, Outcome.reverse(outcome))])
end

fn standing(team: String, outcomes: Iter<Outcome>) -> Standing
    {
        team:,
        won:   count(outcomes, .Win),
        drawn: count(outcomes, .Draw),
        lost:  count(outcomes, .Loss),
    }
end

fn count(outcomes: Iter<Outcome>, wanted: Outcome) -> Int
    Iter.count_by(outcomes, &(&1 == wanted))
end

/// A line of the table: the team's name in a column of 30, then each
/// cell right-aligned in a column of 2.
fn line(team: String, cells: Iter<String>) -> String
    columns = cells |> Iter.map(&String.pad_start(&1, 2)) |> String.join(" | ")
    "${String.pad_end(team, 30)} | ${columns}"
end

// FILE: tournament_test.nomi
import tournament

test "just the header if no input"
    assert tournament.tally([]) == Ok(["Team                           | MP |  W |  D |  L |  P"])
end

test "a win is three points, a loss is zero points"
    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Allegoric Alaskans             |  1 |  1 |  0 |  0 |  3",
        "Blithering Badgers             |  1 |  0 |  0 |  1 |  0",
    ]

    assert tournament.tally(["Allegoric Alaskans;Blithering Badgers;win"]) == Ok(table)
end

test "a win can also be expressed as a loss"
    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Allegoric Alaskans             |  1 |  1 |  0 |  0 |  3",
        "Blithering Badgers             |  1 |  0 |  0 |  1 |  0",
    ]

    assert tournament.tally(["Blithering Badgers;Allegoric Alaskans;loss"]) == Ok(table)
end

test "a different team can win"
    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Blithering Badgers             |  1 |  1 |  0 |  0 |  3",
        "Allegoric Alaskans             |  1 |  0 |  0 |  1 |  0",
    ]

    assert tournament.tally(["Blithering Badgers;Allegoric Alaskans;win"]) == Ok(table)
end

test "a draw is one point each"
    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Allegoric Alaskans             |  1 |  0 |  1 |  0 |  1",
        "Blithering Badgers             |  1 |  0 |  1 |  0 |  1",
    ]

    assert tournament.tally(["Allegoric Alaskans;Blithering Badgers;draw"]) == Ok(table)
end

test "There can be more than one match"
    rows = [
        "Allegoric Alaskans;Blithering Badgers;win",
        "Allegoric Alaskans;Blithering Badgers;win",
    ]

    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Allegoric Alaskans             |  2 |  2 |  0 |  0 |  6",
        "Blithering Badgers             |  2 |  0 |  0 |  2 |  0",
    ]

    assert tournament.tally(rows) == Ok(table)
end

test "There can be more than one winner"
    rows = [
        "Allegoric Alaskans;Blithering Badgers;loss",
        "Allegoric Alaskans;Blithering Badgers;win",
    ]

    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Allegoric Alaskans             |  2 |  1 |  0 |  1 |  3",
        "Blithering Badgers             |  2 |  1 |  0 |  1 |  3",
    ]

    assert tournament.tally(rows) == Ok(table)
end

test "There can be more than two teams"
    rows = [
        "Allegoric Alaskans;Blithering Badgers;win",
        "Blithering Badgers;Courageous Californians;win",
        "Courageous Californians;Allegoric Alaskans;loss",
    ]

    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Allegoric Alaskans             |  2 |  2 |  0 |  0 |  6",
        "Blithering Badgers             |  2 |  1 |  0 |  1 |  3",
        "Courageous Californians        |  2 |  0 |  0 |  2 |  0",
    ]

    assert tournament.tally(rows) == Ok(table)
end

test "typical input"
    rows = [
        "Allegoric Alaskans;Blithering Badgers;win",
        "Devastating Donkeys;Courageous Californians;draw",
        "Devastating Donkeys;Allegoric Alaskans;win",
        "Courageous Californians;Blithering Badgers;loss",
        "Blithering Badgers;Devastating Donkeys;loss",
        "Allegoric Alaskans;Courageous Californians;win",
    ]

    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Devastating Donkeys            |  3 |  2 |  1 |  0 |  7",
        "Allegoric Alaskans             |  3 |  2 |  0 |  1 |  6",
        "Blithering Badgers             |  3 |  1 |  0 |  2 |  3",
        "Courageous Californians        |  3 |  0 |  1 |  2 |  1",
    ]

    assert tournament.tally(rows) == Ok(table)
end

test "incomplete competition (not all pairs have played)"
    rows = [
        "Allegoric Alaskans;Blithering Badgers;loss",
        "Devastating Donkeys;Allegoric Alaskans;loss",
        "Courageous Californians;Blithering Badgers;draw",
        "Allegoric Alaskans;Courageous Californians;win",
    ]

    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Allegoric Alaskans             |  3 |  2 |  0 |  1 |  6",
        "Blithering Badgers             |  2 |  1 |  1 |  0 |  4",
        "Courageous Californians        |  2 |  0 |  1 |  1 |  1",
        "Devastating Donkeys            |  1 |  0 |  0 |  1 |  0",
    ]

    assert tournament.tally(rows) == Ok(table)
end

test "ties broken alphabetically"
    rows = [
        "Courageous Californians;Devastating Donkeys;win",
        "Allegoric Alaskans;Blithering Badgers;win",
        "Devastating Donkeys;Allegoric Alaskans;loss",
        "Courageous Californians;Blithering Badgers;win",
        "Blithering Badgers;Devastating Donkeys;draw",
        "Allegoric Alaskans;Courageous Californians;draw",
    ]

    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Allegoric Alaskans             |  3 |  2 |  1 |  0 |  7",
        "Courageous Californians        |  3 |  2 |  1 |  0 |  7",
        "Blithering Badgers             |  3 |  0 |  1 |  2 |  1",
        "Devastating Donkeys            |  3 |  0 |  1 |  2 |  1",
    ]

    assert tournament.tally(rows) == Ok(table)
end

test "ensure points sorted numerically"
    rows = [
        "Devastating Donkeys;Blithering Badgers;win",
        "Devastating Donkeys;Blithering Badgers;win",
        "Devastating Donkeys;Blithering Badgers;win",
        "Devastating Donkeys;Blithering Badgers;win",
        "Blithering Badgers;Devastating Donkeys;win",
    ]

    table = [
        "Team                           | MP |  W |  D |  L |  P",
        "Devastating Donkeys            |  5 |  4 |  0 |  1 | 12",
        "Blithering Badgers             |  5 |  1 |  0 |  4 |  3",
    ]

    assert tournament.tally(rows) == Ok(table)
end

// Not canonical: the canonical data has no malformed rows.
test "a row that is not a match is an error"
    row = "Allegoric Alaskans;Blithering Badgers;tie"

    assert tournament.tally([row]) == Err(.InvalidRow(row))

    assert tournament.tally(["Allegoric Alaskans;win"])
        == Err(.InvalidRow("Allegoric Alaskans;win"))
end
  • tally takes the rows as a List<String> and returns the table’s lines, as the canonical data gives them.
  • tally returns a Result, with Error.InvalidRow carrying a row that is not home;away;outcome or whose outcome is not win, draw or loss. The canonical data has no malformed rows; the test file adds a case, marked as not canonical.
  • parse_row turns each match into its outcome for both teams, (home, outcome) and (away, Outcome.reverse(outcome)), so the rest of the tally never looks at which team was at home.
  • The standings are Iter.group_by on the team, then a Standing per team with its wins, draws and losses counted. Matches played and points are functions of those three, not fields.
  • The table is one Iter.sort_by whose key is the tuple (Reverse.of(points), team). Tuples compare element by element, so the points decide and the name breaks a tie; Reverse.of puts the most points first.
  • A row of the table and the header are the same line function over the team’s name and five cells, so the column widths are written once.
  • Each canonical case is its own test with rows and table bindings: the tables are several lines each, and a subtests row holding two lists of strings would hide which list is which.