C algorithm on the problem of veal production
- 2020-12-26 05:50:51
- OfStack
An example of C# algorithm is presented in this paper. Share to everybody for everybody reference. The specific analysis is as follows:
Question:
1 calf born, 1 calf born 4 years later, 1 calf born every year thereafter. There is one calf born. How many cows will there be in 20 years?
At first, I thought recursion was better. After a long time, I couldn't figure it out, so I came up with the following method to realize it. The number of the data, i, represents the age of cows, and the value of the array i represents how many cows there are this year
The implementation code is as follows:
const int YEAR = 50;
static void Main(string[] args)
{
int[] yearAmount = new int[YEAR];
yearAmount[0] = 1;
for (int year = 1; year < YEAR; year++)
{
int count = 0;
for (int i = year; i > 0; i--)
{
if (i >= 2)
count += yearAmount[i]; // There are several calves
yearAmount[i] = yearAmount[i - 1]; // The age of the cattle +1
}
yearAmount[0] = count; // The calf was born 0 At the age of
}
int result = yearAmount.Sum();
Console.WriteLine("{0} In total :{1} Head of cattle ", YEAR, result);
Console.Read();
}
Pretty fast!
Hopefully this article has helped you with your C# programming.