Reading the post https://steemit.com/programming/@justyy/python-function-to-solve-the-chicken-and-rabbit-math-problem , I feeled the desire to try it in my favorite language.
Sor first, thank you @justyy for sharing initialy the solving of this litlle math game in Python.
Solving it first on a paper
If we had to solve it only with a pen and a paper with 2 rabbits and 1 chicken ? Let's try !
So with this approach I'm able to get back the initial statement of 2 rabbits and only 1 chicken
Now in Ocaml
let solve_rabbit_and_chicken heads legs =
let get_chicken_from rabbit = heads - rabbit in
let rabbit = (legs - (2 * heads)) / 2 in
let chicken = get_chicken_from rabbit in
Some (rabbit,chicken)
The problem I have now is that I'm not sure the solution is always good. We can have negative values as an answer, or we can have incorrect parameters that's why I have used the Some constructor to return the value.
I need now to add code to detect the situation where there is a problem of consistency between legs and heads or in the result.
So the final code will be :
let solve_rabbit_and_chicken heads legs =
let get_chicken_from rabbit = heads - rabbit in
if heads < 1 || legs < 2 || (legs mod 2 <> 0) then None else
let rabbit = (legs - (2 * heads)) / 2 in
let chicken = get_chicken_from rabbit in
if rabbit < 0 || chicken < 0 then None else
Some (rabbit,chicken)