Instructions
Calculate the points scored in a single toss of a Darts game.
Darts is a game where players throw darts at a target.
In our particular instance of the game, the target rewards 4 different amounts of points, depending on where the dart lands:

- If the dart lands outside the target, player earns no points (0 points).
- If the dart lands in the outer circle of the target, player earns 1 point.
- If the dart lands in the middle circle of the target, player earns 5 points.
- If the dart lands in the inner circle of the target, player earns 10 points.
The outer circle has a radius of 10 units (this is equivalent to the total radius for the entire target), the middle circle a radius of 5 units, and the inner circle a radius of 1.
Of course, they are all centered at the same point — that is, the circles are concentric defined by the coordinates (0, 0).
Given a point in the target (defined by its Cartesian coordinates x and y, where x and y are real), calculate the correct score earned by a dart landing at that point.
Credit
The scoreboard image was created by habere-et-dispertire using Inkscape.
Dig Deeper
hypot for radius
hypot for radius
import kotlin.math.hypot
object Darts {
private const val innerRing = 1.0
private const val middleRing = 5.0
private const val outerRing = 10.0
fun score(x: Number, y: Number): Int {
val toss = hypot(x.toDouble(), y.toDouble())
fun throwWithin(ring: Double) = toss <= ring
if (throwWithin(innerRing)) return 10
if (throwWithin(middleRing)) return 5
if (throwWithin(outerRing)) return 1
return 0
}
}
An object declaration is used to define Darts as essentially a singleton object instantiation of the class.
This is sufficient, since there is no object state that needs to change with each call of the score method.
The object defines private const vals for the rings.
The const values are given meaningful names instead of using the float literals as magic numbers.
A val is immutable, as is a const.
A const val means that the value of the val is known at compile time.
The hypot function is used to calculate the radius of the dart throw from the x and y coordinates.
The throwWithin function returns if the radius is within the ring passed in.
Due to the naming of the function and varables, the if statements read much like natural language.
The throwWithin function is passed the ring.
If it returns true, then the function returns with the score for throwing within that ring.
If the throw is not within a defined ring, then the function returns 0.
Source: Exercism kotlin/darts