Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Darts

darts.livemd

Darts

Resolving

defmodule Darts do
  @type position :: {number, number}

  @doc """
  Calculate the score of a single dart hitting a target
  """
  @spec score(position) :: integer
  def score({x, y}) do
    # L²=sqrt((x_2 - x_1)²+(y_2 - y_1)²)
    dist = :math.sqrt(:math.pow(x,2)+:math.pow(y, 2))

    cond do
      dist > 10 -> 0
      dist > 5 -> 1
      dist > 1 -> 5
      true -> 10
    end
  end
end
x_abs = 0.1
y_abs = 0.1
cond do
  x_abs > 10 or y_abs > 10 -> 0
  x_abs > 5  or y_abs > 5  -> 1
  x_abs > 1  or y_abs > 1  -> 5
  true -> 10
end

Testing

ExUnit.start(auto_run: false)

defmodule DartsTest do
  use ExUnit.Case

  # @tag :pending
  test "Missed target" do
    assert Darts.score({-9, 9}) == 0
  end

  @tag :pending
  test "On the outer circle" do
    assert Darts.score({0, 10}) == 1
  end

  @tag :pending
  test "On the middle circle" do
    assert Darts.score({-5, 0}) == 5
  end

  @tag :pending
  test "On the inner circle" do
    assert Darts.score({0, -1}) == 10
  end

  @tag :pending
  test "Exactly on centre" do
    assert Darts.score({0, 0}) == 10
  end

  @tag :pending
  test "Near the centre" do
    assert Darts.score({-0.1, -0.1}) == 10
  end

  @tag :pending
  test "Just within the inner circle" do
    assert Darts.score({0.7, 0.7}) == 10
  end

  @tag :pending
  test "Just outside the inner circle" do
    assert Darts.score({0.8, -0.8}) == 5
  end

  @tag :pending
  test "Just within the middle circle" do
    assert Darts.score({-3.5, 3.5}) == 5
  end

  @tag :pending
  test "Just outside the middle circle" do
    assert Darts.score({-3.6, -3.6}) == 1
  end

  @tag :pending
  test "Just within the outer circle" do
    assert Darts.score({-7.0, 7.0}) == 1
  end

  @tag :pending
  test "Just outside the outer circle" do
    assert Darts.score({7.1, -7.1}) == 0
  end

  @tag :pending
  test "Asymmetric position between the inner and middle circles" do
    assert Darts.score({0.5, -4}) == 5
  end
end

ExUnit.run()