【发布时间】:2014-11-14 05:14:43
【问题描述】:
我想通过从另一个列表中获取一些其他随机元素来替换列表中的“变异”元素。
private int elitism = 20;
private int population = 1;
private int chance = 100;
private Random rand = new Random();
private List<HeroStats> allHeroes = new List<HeroStats>();
private List<Team> allTeams = new List<Team>();
如果我创建一个团队并对其进行变异,它应该替换当前团队中的 1 个随机元素,但如果我使用 yhe Mutation 方法,则不会发生替换;我得到了同一个团队
public void Mutation()
{
// compute how many individuals will 100% survive
int goodResults= population * elitism / 100;
int index;
int position;
HeroStats old_hero, new_hero;
Team new_team;
for (int i = goodResults; i < allTeams.Count(); i++)
{
if (rand.Next(0, 100) < chance)
{
new_team = allTeams.ElementAt(i);
index = allTeams.IndexOf(new_team);
// select random hero within the team , a team having 5 heros
position = rand.Next(0, 4);
//RetrieveHero(int x) is a method which returns the hero from position x within a team
old_hero = new_team.RetrieveHero(position);
// get a new hero from the hero-list
new_hero = allHeroes.ElementAt(rand.Next(0, 101));
// associate the new value to the genome
new_team.Remove(old_hero);
new_team.Add(new_hero);
allTeams[index] = new_team;
}
}
}
例如:考虑团队 a = [ 1 2 3 4 5]
team a 经历 Mutation 之后,它可能看起来像这样
team a = [1, 2, 3, 4, R] 或 team a = [1, P, 3, 4, 5] , 或团队 a = [1, 2, 3, 99, 5]
为什么我的代码表现得这么奇怪?
【问题讨论】:
-
预期的输出是什么,或者你得到了什么让它表现得如此奇怪?
-
它到底在做什么让你觉得它的行为很奇怪?
-
我只创建了一个团队,打印它,使用该团队的方法并再次打印新团队来测试它,它没有改变任何东西
-
您能否尝试从您的示例中删除不相关的代码,同时使变量范围尽可能小。还有一些复杂的代码实现了
index=i(index=allTeams.IndexOf(allTeams.ElementAt(i)),目的不明确 - 看看你是否也可以清理它。 -
就目前而言,代码看起来不错(最后一个赋值绝对没有做任何事情,但它不应该伤害任何东西)。你能检查/显示
Add和Remove方法吗?你确定你曾经进入过if声明吗?
标签: c# list genetic-algorithm mutation