|
| 1 | +# `hypot` for radius |
| 2 | + |
| 3 | +```kotlin |
| 4 | +import kotlin.math.hypot |
| 5 | + |
| 6 | +object Darts { |
| 7 | + private const val innerRing = 1.0 |
| 8 | + private const val middleRing = 5.0 |
| 9 | + private const val outerRing = 10.0 |
| 10 | + |
| 11 | + fun score(x: Number, y: Number): Int { |
| 12 | + val toss = hypot(x.toDouble(), y.toDouble()) |
| 13 | + fun throwWithin(ring: Double) = toss <= ring |
| 14 | + |
| 15 | + if (throwWithin(innerRing)) return 10 |
| 16 | + if (throwWithin(middleRing)) return 5 |
| 17 | + if (throwWithin(outerRing)) return 1 |
| 18 | + return 0 |
| 19 | + } |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +An [object declaration][object] is used to define `Darts` as essentially a [singleton][singleton] object instantiation of the class. |
| 24 | +This is sufficient, since there is no object state that needs to change with each call of the `score` method. |
| 25 | + |
| 26 | +The object defines [private][visibility] [`const`][const] [val][variables]s for the rings. |
| 27 | +The `const` values are given meaningful names instead of using the float literals as [magic numbers][magic-numbers]. |
| 28 | +A `val` is immutable, as is a `const`. |
| 29 | +A `const` `val` means that the value of the `val` is known at compile time. |
| 30 | + |
| 31 | +The [`hypot`][hypot] function is used to calculate the [radius][radius] of the dart throw from the `x` and `y` coordinates. |
| 32 | + |
| 33 | +The `throwWithin` function returns if the radius is within the ring passed in. |
| 34 | + |
| 35 | +Due to the naming of the function and varables, the `if` statements read much like natural language. |
| 36 | + |
| 37 | +The `throwWithin` function is passed the ring. |
| 38 | +If it returns `true`, then the function returns with the score for throwing within that ring. |
| 39 | + |
| 40 | +If the throw is not within a defined ring, then the function returns `0`. |
| 41 | + |
| 42 | +[object]: https://kotlinlang.org/docs/object-declarations.html#object-declarations-overview |
| 43 | +[singleton]: https://en.wikipedia.org/wiki/Singleton_pattern |
| 44 | +[visibility]: https://kotlinlang.org/docs/visibility-modifiers.html |
| 45 | +[const]: https://www.geeksforgeeks.org/whats-the-difference-between-const-and-val-in-kotlin/ |
| 46 | +[variables]: https://kotlinlang.org/docs/basic-syntax.html#variables |
| 47 | +[magic-numbers]: https://en.wikipedia.org/wiki/Magic_number_(programming) |
| 48 | +[hypot]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.math/hypot.html |
| 49 | +[radius]: https://www.mathopenref.com/coordbasiccircle.html |
| 50 | + |
0 commit comments