Python Function to Solve the Chicken and Rabbit Math Problem

in programming •  4 years ago  (edited)

Problem statement: Given a cage that has R rabbits and C chicken, and we know there are H heads and L legs. So find out the value of R and C (how many rabbits and how many chicken)

Math Equation to solve chicken and rabbit problem


We can express the problem using Math equations:

R + C = H
4*R + 2*C = L

We know a rabbit has four legs and a chicken has two legs. Both rabbit and chicken have only 1 head (of course!). In the above equation, we have 2 unknowns R and C, and the H and L are given, and thus we can solve the equation for the unknowns.

Bruteforce Algorithm to solve Chicken and Rabbit


We can bruteforce R or C from 0 to the maximum H value, and then check if the legs are the same as L.

def solve(heads, legs):
  r = 0
  while r <= heads:
    c = heads - r
    if 4 * 4 + 2 * c == legs:
      return [r, c]
    r += 1
  return None # can't find any valid solution

There are only H possibilities and sure this can be solved by computer in no time.

--EOF (The Ultimate Computing & Technology Blog) --

Reposted to Algorithms, Blockchain, and Cloud

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Support me

If you like my work, please:

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
  ·  4 years ago 

Thanks!

  ·  4 years ago 

Thanks!

  ·  4 years ago 

🈵👏🏻行长!shop

  ·  4 years ago 

你好鸭,justyy!

@annepink给您叫了一份外卖!

花生阿姨牌花生

吃饱了吗?跟我猜拳吧! 石头,剪刀,布~

如果您对我的服务满意,请不要吝啬您的点赞~

Now it will be interesting to create a function using equation system approach to show another way to solve it without a loop.

  ·  4 years ago 

Yes.!