Python Function to Solve the Chicken and Rabbit Math Problem


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:

tex_0db5097e396ff385227b7d5b9dad07ee Python Function to Solve the Chicken and Rabbit Math Problem algorithms math python
tex_2346953bf4fb42ed8d1e57a708038735 Python Function to Solve the Chicken and Rabbit Math Problem algorithms math python

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.

1
2
3
4
5
6
7
8
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
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

python3-solve-rabbit-and-chicken-768x1024 Python Function to Solve the Chicken and Rabbit Math Problem algorithms math python

whiteboard-rabbit-chicken-1024x768 Python Function to Solve the Chicken and Rabbit Math Problem algorithms math python

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

Actually, we can solve the linear equation with 2 unknowns and implement the solution in O(1) constant time: Teaching Kids Programming – Linear Equation with Two Unknowns (Chicken and Rabbit Problem)

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
453 words
Last Post: Algorithms to Check if a String is a Subsequence String of Another String
Next Post: Two Pointer with Sliding Window Algorithm to Compute the Longest Substring with At Most K Distinct Characters

The Permanent URL is: Python Function to Solve the Chicken and Rabbit Math Problem

Leave a Reply