您的位置:首页 > 其它

奶牛问题,别人写的,自己试了一下.

2009-12-09 17:17 218 查看
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace CowCount
7 {
8 public class Cow
9 {
10 public int Age { get; set; }
11 public int Generation { get; set; }
12 public int Id { get; set; }
13 public int ParentId { get; set; }
14
15 public Cow() { }
16
17 public Cow(int age, int generation, int id, int parentId)
18 {
19 this.Age = age;
20 this.Generation = generation;
21 this.Id = id;
22 this.ParentId = parentId;
23 }
24 }
25 class Program
26 {
27 static List<Cow> listCows = new List<Cow>();
28 static int maxYear = 20;
29 public static void GetBirth(int year)
30 {
31 List<Cow> listBornCows = new List<Cow>(); //添加新生的奶牛
32 Cow firstCow = new Cow(1, 1, 1, 0);
33 listCows.Add(firstCow);
34 for (int i = 0; i < year; i++)
35 {
36 foreach (Cow item in listCows)
37 {
38 item.Age++; //年龄自增
39 if (item.Age > 4)
40 {
41 Cow birth = new Cow(1,item.Generation + 1, listCows.Count + 1, item.Id);
42 listBornCows.Add(birth); //添加新生的奶牛
43 }
44 }
45 listCows.AddRange(listBornCows);
46 listBornCows.Clear();
47 }
48 }
49
50 public static List<Cow> GetCowByParentId(int parentId)
51 {
52 List<Cow> result = new List<Cow>();
53 foreach (Cow item in listCows)
54 {
55 if (item.ParentId == parentId)
56 result.Add(item);
57 }
58 return result;
59 }
60
61 public static void ShowCows()
62 {
63 int count = 0;
64 if (listCows != null)
65 {
66 count = listCows.Count;
67 }
68 Console.WriteLine(string.Format("After 20 years,cows count:{0}", count.ToString()));
69
70 //按照所属于母亲显示对应奶牛数
71 int maxParentId = 0;
72 if (listCows.Count > 0)
73 {
74 listCows.Sort(delegate(Cow left, Cow right) { return right.ParentId.CompareTo(left.ParentId); });
75 maxParentId = listCows[0].ParentId;
76 }
77 for (int i = 0; i < maxParentId; i++)
78 {
79 List<Cow> listModels = GetCowByParentId(i);
80 Console.WriteLine(string.Format("Cow_{0}'s children as follows:",i));
81 if(listModels.Count == 0)
82 {
83 Console.WriteLine("Has no any child!");
84
85 }
86 else
87 {
88 foreach (Cow item in listModels)
89 {
90 Console.WriteLine(string.Format("Age:{0},Id:{1},Generation:{2}", item.Age, item.Id, item.Generation));
91 }
92 }
93 }
94 }
95 static void Main(string[] args)
96 {
97 GetBirth(maxYear);
98 Console.WriteLine(listCows.Count);
99 //ShowCows();
Console.ReadLine();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: