Problem:
A ewd has a life cycle of 5 years. It will give birth to a EWD at the end of 2nd and the end of 4th, and will die at the end of 5th. Ask if the farm has one EWD at the beginning. After N years, how many ewes will the farm have?
Resolution 1)
You don't have to pay attention to the logic of this question, or you don't have to worry about the formulas hidden in it. You just need to understand it according to the normal life and natural laws of people.
First, it virtualizes a ewd. This EWD has only one attribute, that is, age:
ClassSheep {
Public IntAge = 0;//The age of a new goat is 0 by default.
}
Then this person has a counter to calculate the number of pastures and sheep in N years.The working principle of this counter is:The calculation starts from the unit of year. After each year, there are sheep in the circular grazing place:
(1) Add 1 to the age of the goat,
(2) If a mother-in-law is two or four years old today, let her have a lamb,
(3) If the mother-in-law is five years old, let him pass away and clean up the farm.
// N is the number of years passed
Public Static Int Getsheeps ( Int N ){
// Sheeps indicates the entire ecological circle of the goat
Arraylist <sheep> sheeps = New Arraylist <sheep> ();
Sheeps. Add ( New Sheep ());
List <sheep> addsheeps = New Arraylist <sheep> (); // The new goat to be added to the ecosystem
List <sheep> delsheeps = New Arraylist <sheep> (); // To be deleted from the ecosystem
For ( Int I = 1; I <= N; I ++ ){
For (Sheep S: sheeps ){
S. Age ++;
If (S. Age = 2 | S. Age = 4 ){// The goat is still alive
Addsheeps. Add ( New Sheep ());
} Else If (S. Age = 5 ){ // Goat death, add to the delete list delsheeps, wait for deletion
Delsheeps. Add (s );
}
}
Sheeps. addall (addsheeps );
Sheeps. removeall (delsheeps );
Addsheeps. Clear (); // Clear addsheeps
Delsheeps. Clear (); // Clear the elements in the list to be deleted
}
Return Sheeps. Size (); // The total number of sheep is the number of sheep in the sheepsphere.
}
Resolution 2)
Any problem of "Life two, two life three, three life" is undoubtedly solved by recursion.Algorithm(By the way, it is associated with the Fibonacci series ). Below is a completeCode:
Public Class Mymain {
Public Static Int Get ( Int Year)
{
Int Num = 1; // The initial sheep number
For ( Int I = 1; I <= year; I ++ ){
If (I = 2 ){
Num + = get (year-2 );
} Else If (I = 4 ){
Num + = get (year-4 );
} Else If (I = 5 ){
Num --;
}
}
Return Num;
}
Public Static Void Main (string [] ARGs ){
String line1 = "";
String line2 = "";
For ( Int I = 1; I <= 18; I ++ ){
Line1 + = "no." + I + "year" + "";
Line2 + = get (I) + "";
}
System. Out. println (line1 );
System. Out. println (line2 );
}
}