小弟問一到母雞下蛋的算法題目
一開始有一只母雞,到第四天會下一個蛋,以後每一天都會下一個蛋。四天後,第一個蛋變成了母雞,四天後,第二只母雞又會下一個蛋。同時每只雞的生命週期為10天。10天後死亡。
請問N天後,一共有多少只雞,多少個蛋....
小弟考慮過用兩個vector分別存放雞和蛋。雞比較容易,4天誕生,10天死亡。
只要是蛋怎麼計算?
舉個例子:
1. hen:1 egg:0
2 hen:1 egg:0
3 hen:1 egg:0
4 hen:1 egg:1
5 hen:1 egg:2
6 hen:1 egg:3
7 hen:1 egg:4
8 hen:2 egg:4 (第4天的蛋變雞了,蛋減1,但第一只母雞還會繼續下蛋)
9 hen:3 egg:4 (第5天的蛋變雞了,蛋減1,但第一只母雞還會繼續下蛋)
10 hen:3 egg:3 (第一隻雞這天死了,第6天的蛋變雞了,蛋減1)
11 hen:4 egg:3(第7天的蛋變雞了,蛋減1。母雞死了,不會再下蛋)
12 hen:5 egg:3 (第8天的蛋變雞了,蛋減1。第8天蛋生的母雞開始下蛋)
.....
各位大大能提供一下思路嗎?下弟謝過
[解决办法]
另类斐波那契数列,
f(n) = f(n - 1) + f(n - 8) - f(n - 10) 鸡的数量
lz自己推算一下蛋的数量吧,也是这个思路
[解决办法]
Result getResult(int day) { List<chiken> chikens = new List<chiken>() { chiken.get(10,1) }; List<Egg> eggs = new List<Egg>(); for (int i = 1; i <= day; i++) { List<chiken> tmpChiken=new List<chiken> (); foreach (chiken c in chikens) { if (c.currentLife >= 4) eggs.Add(Egg.get(4, 1)); else if (c.currentLife > c.Life) tmpChiken.Add(c); else c.currentLife++; } remove<chiken>(chikens, tmpChiken); List<Egg> tmpEgg = new List<Egg>(); foreach (Egg c in eggs) { if (c.currentLife > c.Life) { chikens.Add(chiken.get(10, 1)); tmpEgg.Add(c); } else c.currentLife++; } remove<Egg>(eggs, tmpEgg); } return new Result() { chiken=chikens.Count , egg=eggs.Count }; } void remove<T>(List<T> source, List<T> some) { foreach (var i in some) source.Remove(i); } public class chiken { public static chiken get(int life, int currentlife) { return new chiken() { Life=life, currentLife =currentlife }; } public int Life { set; get; } public int currentLife { set; get; } } public class Egg { public static Egg get(int life, int currentlife) { return new Egg() { Life = life, currentLife = currentlife }; } public int Life { set; get; } public int currentLife { set; get; } } public class Result { public int chiken { set; get; } public int egg { set; get; } }