Last Friday night, I saw the following interview question on a group:
Topic:
A farmer buys a calf, and the calf, in its fourth year, will have a calf every year, and the calf will grow toBeginning of the fourth yearAfter N years, how many cows will the farmer have?
Not taking into account other circumstances, like death, escape, etc
Train of thought
A fertile cow is called a cow, and an infertile cow is called a calf
Year 1:1 calf
Year 2:1 calf
Year 3:1 calf
Year 4:1 calf, 1 cow – 2 cows
Year 5:2 calves, 1 cow – 3 cows
Year 6:3 calves, 1 cow – 4 cows
Year 7:4 calves, 2 cows – 6 cows
Year 8:6 calves, 3 cows – 9 cows
.
implementation
As a graph cutter, we use javascript to implement ~
// A farmer buys a calf. The calf will have a calf every year in its fourth year. The calf will also have a calf every year in its fourth year.
// Do not consider other cases
class Cow {
constructor() {
this.age = 1
}
addAge() {
this.age++
}
isCanBirth() {
return this.age >= 4; }}function init(year) {
let arr = [new Cow()];
for(let i = 1; i <= year; i++) {
for(let j = 0; j < arr.length; j ++) {
let cow = arr[j];
if(cow.isCanBirth()) {
arr.push(new Cow())
} else {
cow.addAge()
}
}
console.log(The first `${i}Years,${arr.length}A cow `)
}
}
init(10)
Copy the code
The results of the above program are as follows:
"In year 1, I have 1 cow."
"In year 2, I have 1 cow."
"In year 3, I have 1 cow."
"In year 4, I have 2 cows."
"In year 5, I have 3 cows."
"In year 6, we have 4 cows."
"In the seventh year, we have six cows."
"In the eighth year, there are 9 cows."
"In year 9, there are 13 cows."
"In year 10, we have 19 cows."
Copy the code
I would like you to point out if there are any loose points above. The related code shows the address how_many_cow from codepen.
The latter
-
The farmer raises cattle
-
More – Jimmy Blog