Setup
Your friend likes to go to the horse races and gamble on which horses will finish first, second, and third place. Unfortunately, he doesn't know how many horses will be entering until he gets to the track.
Write a function that will take any number of horses as its only argument. This function must return the total number of different combinations of winners for the gold, silver, and bronze medals.
For example, if there are 15 horses, there are 2730 possible unique combinations of winners. If the number of horses is 3 or less, return the input value. If the number of horses is not an integer, return undefined
.
Examples
horses(15), 2730, true)
horses(2.5), undefined, false)
Tests
horses(12)
horses(2)
horses(11)
horses(a)
Good luck!
This challenge comes from tu6619 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (13)
The code (F#)
As F# is a strongly typed language, no need to check n is an integer - it is. Idiomatically, "undefined" in F# is handled with the Option monad, so we return either None or Some result.
The actual calculation is trivial; n * (n-1) * (n-2)
Good old factorials. I had fun with this one. Feel free to give advice if I can make my code better!
JS
CodePen
Edit: forgot to convert the input to a number making all of the numbers that go through the function a string
The word "combinations" being used here provides us with a good jumping-off point to figure out the solution - combinatorics! We can calculate the
n
choosek
/binomial coefficient for the horses, wheren
is the total number of horses, andk
is equal to 3, since we're looking for 3 horses (gold, silver, and bronze winners). From there, we need to take into account that ordering - which horse won which position - matters to us; mathematical combinations are sets in which order doesn't normally matter. We'll need permutations for that part.So, knowing that the number of permutations for a set of
n
elements is equal ton!
, we can multiply the result of ourn
choosek
by 6 (which is just a shorthand for multiplying by3!
, as3! = 6
). Putting that all together with a little bit of error checking, we have the following short Python solution:edit: forgot to add code to check for floating-point numbers as input, whoops
Nice solution, you could also use the
itertools
package:dev.to/rafaacioly/comment/jkno
Here's my submission while I'm learning Nim.
Shortest answer I could think of:
And in Standard ML, since it has type checking I can skip the int check:
Python solution 🐍
My JavaScript solution:
Ruby
Yes, I said that in my post.
However, I misread the challenge, and thought that "undefined" should be returned when n <= 3, although it should actually return the input.