随笔 - 268  文章 - 0  评论 - 1028  阅读 - 160万

再谈奶牛问题

在博客园上看到很多人讨论的”在csdn上看到奶牛问题,写了下算法“和“奶牛问题”,觉得好玩,自己尝试着用面向对象的方法算了一下,练练手,没有技术含量,记录下来。
一、问题还原
一只刚出生的小牛,4年后生一只小牛,以后每年生一只。现有一只刚出生的小牛,问20年后共有牛多少只?

ps:看到很多人在原题处留言说这题出的不严谨云云。下面的所有实现都是在理想状态下,特此声明。
二、具体实现
1、奶牛实体类

复制代码
代码
  public class Cow
    {

        
public Cow()
        {

        }

        
public Cow(int age, int generation, int id, int parentId)
        {
            
this.Age = age;
            
this.Generation = generation;
            
this.Id = id;
            
this.ParentId = parentId;
        }

        
/// <summary>
        
/// 岁数
        
/// </summary>
        public int Age { getset; }

        
/// <summary>
        
/// 第几代
        
/// </summary>
        public int Generation { getset; }

        
/// <summary>
        
/// 唯一标识 id
        
/// </summary>
        public int Id { getset; }

        
/// <summary>
        
/// 母亲id
        
/// </summary>
        public int ParentId { getset; }
    }
复制代码

 2、生奶牛方法(非递归)

复制代码
代码
        static List<Cow> listCows = new List<Cow>();
        
public static void GetBirth(int year)
        {
            List
<Cow> listBornCows = new List<Cow>();//用于添加新生的奶牛
            Cow firstCow = new Cow(1110);
            listCows.Add(firstCow);
            
for (int i = 0; i < year; i++)
            {
                
foreach (Cow item in listCows)
                {
                    item.Age
++//年龄自增
                    if (item.Age > 4)
                    {
                        
//生出一头牛
                        Cow birth = new Cow(1, item.Generation + 1, listCows.Count + 1, item.Id);
                        listBornCows.Add(birth); 
//添加新生的奶牛
                    }
                }
                listCows.AddRange(listBornCows);
                listBornCows.Clear();
            }
        }
复制代码

 3、输出
下面的显示是按照母亲id来显示结果的,您也可以改成按照第几代或者岁数显示。

复制代码
代码
        public static List<Cow> GetCowByParentId(int parentId)
        {
            List
<Cow> result = new List<Cow>();
            
foreach (Cow item in listCows)
            {
                
if (item.ParentId == parentId)
                {
                    result.Add(item);
                }
            }
            
return result;
        }

        
public static void ShowCows()
        {
            
int count = 0;
            
if (listCows != null)
            {
                count 
= listCows.Count;
            }
            Console.WriteLine(
string.Format("After 20 years,cows count:{0}", count.ToString()));

            
/*下面按照所属母亲(ParentId)显示对应奶牛数*/
            
int maxParentId = 0;
            
if (listCows.Count > 0)
            {
                
//按照所属母亲 逆序排序
                listCows.Sort(delegate(Cow left, Cow right) { return right.ParentId.CompareTo(left.ParentId); });
                maxParentId 
= listCows[0].ParentId;
            }
            
for (int i = 0; i < maxParentId; i++)
            {
                List
<Cow> listModels = GetCowByParentId(i);
                Console.WriteLine(
string.Format("Cow_{0}'s children as follows:", i));
                
if (listModels.Count == 0)
                {
                    Console.WriteLine(
"Has no any child!");
                }
                
else
                {
                    
foreach (Cow item in listModels)
                    {
                        Console.WriteLine(
string.Format("Age:{0},Id:{1},Generation:{2}", item.Age, item.Id, item.Generation));
                    }
                }
            }
        }
复制代码

 最后贴一下完整代码:

复制代码
代码
   class Program
    {
        
static List<Cow> listCows = new List<Cow>();
        
static int maxYear = 20;
        
public static void GetBirth(int year)
        {
            List
<Cow> listBornCows = new List<Cow>();//用于添加新生的奶牛
            Cow firstCow = new Cow(1110);
            listCows.Add(firstCow);
            
for (int i = 0; i < year; i++)
            {
                
foreach (Cow item in listCows)
                {
                    item.Age
++//年龄自增
                    if (item.Age > 4)
                    {
                        
//生出一头牛
                        Cow birth = new Cow(1, item.Generation + 1, listCows.Count + 1, item.Id);
                        listBornCows.Add(birth); 
//添加新生的奶牛
                    }
                }
                listCows.AddRange(listBornCows);
                listBornCows.Clear();
            }
        }

        
public static List<Cow> GetCowByParentId(int parentId)
        {
            List
<Cow> result = new List<Cow>();
            
foreach (Cow item in listCows)
            {
                
if (item.ParentId == parentId)
                {
                    result.Add(item);
                }
            }
            
return result;
        }

        
public static void ShowCows()
        {
            
int count = 0;
            
if (listCows != null)
            {
                count 
= listCows.Count;
            }
            Console.WriteLine(
string.Format("After 20 years,cows count:{0}", count.ToString()));

            
/*下面按照所属母亲(ParentId)显示对应奶牛数*/
            
int maxParentId = 0;
            
if (listCows.Count > 0)
            {
                
//按照所属母亲 逆序排序
                listCows.Sort(delegate(Cow left, Cow right) { return right.ParentId.CompareTo(left.ParentId); });
                maxParentId 
= listCows[0].ParentId;
            }
            
for (int i = 0; i < maxParentId; i++)
            {
                List
<Cow> listModels = GetCowByParentId(i);
                Console.WriteLine(
string.Format("Cow_{0}'s children as follows:", i));
                
if (listModels.Count == 0)
                {
                    Console.WriteLine(
"Has no any child!");
                }
                
else
                {
                    
foreach (Cow item in listModels)
                    {
                        Console.WriteLine(
string.Format("Age:{0},Id:{1},Generation:{2}", item.Age, item.Id, item.Generation));
                    }
                }
            }
        }

        
static void Main(string[] args)
        {
            GetBirth(maxYear);
            ShowCows();
            Console.ReadLine();
        }
    }
复制代码



 

posted on   JeffWong  阅读(783)  评论(4编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
< 2009年12月 >
29 30 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2
3 4 5 6 7 8 9

I know how to make it works and I want to know how it works.
点击右上角即可分享
微信分享提示