public static void Update_Generation(aCitizen New_Citizen) { int Max_Index = Heap_Max.Find_First_Best(); if (New_Citizen.nAttacks < Citizen[Max_Index].nAttacks) { Heap_Min.Pop(Heap_Min.pos[Max_Index]); Heap_Max.Pop(Heap_Max.pos[Max_Index]); Citizen[Max_Index].Assign(New_Citizen); Heap_Min.Push(Citizen[Max_Index].nAttacks, Max_Index); Heap_Max.Push(Citizen[Max_Index].nAttacks, Max_Index); } }
public static void Init() { Citizen = new aCitizen[Population]; for (int i = 0; i < Population; i++) { Citizen[i] = new aCitizen(N); Citizen[i].Randomize(); Citizen[i].Local_Optimization(); } Heap_Min = new Heap(Population, true); Heap_Max = new Heap(Population, false); for (int i = 0; i < Population; i++) { Heap_Min.Push(Citizen[i].nAttacks, i); Heap_Max.Push(Citizen[i].nAttacks, i); } }
public static void Genetic_Algorithm() { int nGenerations = 0; result = new aCitizen(N); while (true) { nGenerations++; System.out.println("\nGeneration " + nGenerations); int index1 = Heap_Min.Find_First_Best(); System.out.println("Minimum of attacking: " + Citizen[index1].nAttacks); if (Citizen[index1].nAttacks == 0) { found = true; result = Citizen[index1]; break; } int index2 = Heap_Min.Find_Second_Best(); Update_Generation(index1, index2); while (true) { index1 = Random_Int(Population); index2 = Random_Int(Population); if (index1 != index2) break; } Update_Generation(index1, index2); index1 = Heap_Min.Find_First_Best(); index2 = Heap_Max.Find_Second_Best(); Update_Generation(index1, index2); if (nGenerations == Max_nGenerations) break; } result = Citizen[Heap_Min.Find_First_Best()]; }