Member-only story
JavaScript Algorithm: The Farm Problem
We create a function called animals
that accepts three integers: chickens
, cows
, and pigs
.
In this problem, you are given the number of chickens, cows, and pigs a farmer has on his farm. The goal of the function is to output the number of legs of all the animals on the farm.
Here are the number of legs each animal has (in case you forgot):
chickens = 2 legs
cows = 4 legs
pigs = 4 legs
For every animal the farmer has, you count the number of legs. All you have to do is output the total.
Example:
animals(1, 2, 3) // 22
From the example above, you see that on the farm, there are:
1 chicken
2 cows
3 pigs
We calculate the number of legs for each animal:
1 chicken = 1 * 2= 2
2 cows = 2 * 4 = 8
3 pigs = 3 * 4 = 12
Once we get the sum of all of the legs, we get our total:
2 + 8 + 12 = 22
When we write our function, we pretty much do the same thing.