我想通过从另一个列表中获取一些其他随机元素来替换列表中的“变异”元素。
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
Method ,则不会发生替换;我得到了同一个团队
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 之后,它可能看起来像这个
团队 a = [1, 2, 3, 4, R] 或团队 a = [1, P, 3, 4, 5] 或 team a = [1, 2, 3, 99, 5]
为什么我的代码行为如此奇怪?