/// <summary> /// Výběrová funkce => Turnaj mezi 2 jedinci /// Náhodně vyberu 2 jedince z celé populace. /// Podle getDistance funkce vyberu lepšího jedince. (Kratší vzdálenost = lepší) /// </summary> /// <returns>Invidual (Jedinec)</returns> private Invidual select() { var rnd = new Random(); int i1 = rnd.Next(0, Algorithm.POPULATION_SIZE); int i2 = rnd.Next(0, Algorithm.POPULATION_SIZE); while (i1 == i2) { i2 = rnd.Next(0, Algorithm.POPULATION_SIZE); } Invidual a = this.pCurrent[i1]; Invidual b = this.pCurrent[i2]; if (a.getDistance() < b.getDistance()) { return(a); } else { return(b); } }
/// <summary> /// Konstruktor s argumentem -> Tvorba jedince ze 2 rodičů /// </summary> /// <param name="p1">Rodič 1</param> /// <param name="p2">Rodič 2</param> public Invidual(Invidual p1, Invidual p2) { var rnd = new Random(); int a = rnd.Next(0, 2); if (a == 0) { for (int i = 0; i < Algorithm.CROSSIN_POINT; i++) { this.sequence[i] = p1.sequence[i]; } for (int i = Algorithm.CROSSIN_POINT; i < Algorithm.LENGTH; i++) { this.sequence[i] = p2.sequence[i]; } } else { for (int i = 0; i < Algorithm.CROSSIN_POINT; i++) { this.sequence[i] = p2.sequence[i]; } for (int i = Algorithm.CROSSIN_POINT; i < Algorithm.LENGTH; i++) { this.sequence[i] = p1.sequence[i]; } } if (getDuplicity() > 0) { fixMe(); } }
/// <summary> /// Konstruktor /// Naplním populaci jedinci /// Na začátku jsou jedinci generováni náhodně /// </summary> public Population() { this.pCurrent = new List <Invidual>(); this.pNext = new List <Invidual>(); this.best = null; for (int i = 0; i < Algorithm.POPULATION_SIZE; i++) { this.pCurrent.Add(new Invidual()); } this.updateBest(); }
/// <summary> /// Projdu celou populaci a aktializuji nejlepšího jedince. /// Tohoto jedince držím v proměnné Invidual best /// </summary> private void updateBest() { this.best = null; foreach (Invidual iTmp in this.pCurrent) { if (this.best == null) { this.best = iTmp; } else { if (iTmp.getDistance() < this.best.getDistance()) { this.best = iTmp; } } } }
/// <summary> /// Zlepšující funkce /// S 80% šancí (nebo Algorithm.P_CROSSOVER) aplikuji operátor křížení /// S 20% šancí (nebo Algorithm.P_MUTATION) apliukuji operátor mutace /// Aktualizuji populaci po křížení a mutaci /// </summary> public void improve() { var rnd = new Random(); this.pNext.Clear(); foreach (Invidual iTmp in this.pCurrent) { Invidual iNew; if (rnd.Next(1, 100) < Algorithm.P_CROSSOVER) { iNew = new Invidual(this.select(), this.select()); } else { iNew = this.select(); } if (rnd.Next(1, 100) < Algorithm.P_MUTATION) { iNew.mutate(); } this.pNext.Add(iNew); } this.pCurrent.Clear(); foreach (Invidual iTmp in this.pNext) { this.pCurrent.Add(iTmp); } this.updateBest(); }