Setup
Your friend likes to go to the horse races and gamble on which horses will finish first, second, and third place. Unfortunately, h...
For further actions, you may consider blocking this person and/or reporting abuse
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.
Shouldn't that be "less than 3"? Shouldn't
horses(3)
return 6?In Go.