我想替换" Mutate"列表中的元素,通过从另一个列表中获取一些其他随机元素。
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
经历一次变异之后,它可能看起来像这样的团队a = [1,2,3,4,R],或团队a = [1,P,3, 4,5],或团队a = [1,2,3,99,5]
为什么我的代码表现得如此奇怪?
答案 0 :(得分:0)
我设法通过在Team
类中添加一个方法解决问题:
public void ReplaceHero(HeroStats hero,HeroStats new_Hero)
{
for (int i = 0; i < 5;i++ )
if (team.ElementAt(i).Equals(hero))
{
team.Remove(hero);
team.Add(new_Hero);
}
}
如果我能做出任何改进,我真的很感激了解它们。