请教一个使用c#平均分水果的程序或者思路 非常感谢! |
|
public class Person { public int AppleCount { get; set; } } static void AllotApple(List<Person> persons, int totalApples) { while (totalApples > 0) { var person = persons.OrderBy(x => x.AppleCount).First(); person.AppleCount++; totalApples--; } persons.ForEach(x => { Console.WriteLine(x.AppleCount); }); } 调用方法 List<Person> persons = new List<Person>() { new Person() { AppleCount = 1 }, new Person() { AppleCount = 5 }, new Person() }; AllotApple(persons, 20); |
|
大致上要满足
情景1对应的输入参数为(fruitdistributecount:5,peoplecount:3,fruitorgcount:0,0,0) 输出结果为2,2,1 情景2对应的输入参数为(fruitdistributecount:1,peoplecount:3,fruitorgcount:1,3,0) 输出结果为0,0,1 |
|
20分 |
public class Person { public int AppleNow { get; set; } public int AppleAdd { get; set; } } static void AllotApple(List<Person> persons, int totalApples) { while (totalApples > 0) { var person = persons.OrderBy(x => x.AppleNow + x.AppleAdd).First(); person.AppleAdd++; totalApples--; } persons.ForEach(x => { Console.WriteLine(x.AppleAdd);//这就是你要的分配数据 Console.WriteLine(x.AppleAdd + x.AppleNow);//这是最终分配时每个人的苹果总数量 Console.WriteLine("##################"); }); } 都这样子了还不会改下代码啊…… List<Person> persons = new List<Person>() { new Person() { AppleNow = 1 }, new Person() { AppleNow = 5 }, new Person() }; AllotApple(persons, 20); |
非常感谢,我第一次回复的时候还没有看到你的答案
|
|
static void AllotApple(List<Person> persons, int totalApples) { if (persons.Count < 2) { throw new Exception("如果要分配,那人数至少要二人"); } while (totalApples > 0) { var tmpPersons = persons.OrderBy(x => x.AppleNow + x.AppleAdd).Take(2).ToList(); var addApples = Math.Min(totalApples, tmpPersons[1].AppleAdd + tmpPersons[1].AppleNow - tmpPersons[0].AppleAdd - tmpPersons[0].AppleNow); if (addApples == 0) { addApples = 1; } tmpPersons[0].AppleAdd += addApples; totalApples -= addApples; Console.WriteLine("分配数量:" + addApples); } persons.ForEach(x => { Console.WriteLine(x.AppleAdd);//这就是你要的分配数据 Console.WriteLine(x.AppleAdd + x.AppleNow);//这是最终分配时每个人的苹果总数量 Console.WriteLine("##################"); }); } 再写个改善代码,可以减少分配次数 |
|
学习中……
|