private void RemoveGene(int i) { Array.Copy(Genes, i + 1, Genes, i, GenesLength - (i + 1)); var move = new TMove(); move.Decode((int)Genes[GenesLength - 1]); move.Axis = (move.Axis + 1) % 3; Genes[GenesLength - 1] = move.Encode(); }
private void button1_Click(object sender, EventArgs e) { for (int i = 0; i < 25; i++) { var code = Rnd.Next(9 * RubikCube.N); var move = new TMove(); move.Decode(code); Moves.Add(move); } MoveTimer.Start(); }
public void LoadSolutions() { var fs = new FileStream(SolutionPath, FileMode.OpenOrCreate); var reader = new BinaryReader(fs); while (reader.BaseStream.Position < reader.BaseStream.Length) { var key = reader.ReadString(); var movesCount = reader.ReadInt32(); var moves = new List <TMove>(); for (int i = 0; i < movesCount; i++) { var move = new TMove(); move.Decode(reader.ReadInt32()); moves.Add(move); } Solutions.Add(key, moves); } fs.Close(); }
public double OnEvaluate(TChromosome specimen) { var cube = new RubikCube(RubikCube); var bestFitness = double.MaxValue; for (int len = 0; len < specimen.Genes.Length; len++) { var move = new TMove(); move.Decode((int)specimen.Genes[len]); cube.MakeMove(move); var fitness = cube.Evaluate(); if (fitness < bestFitness) { bestFitness = fitness; (specimen as RubikGenome).MovesCount = len + 1; } } specimen.Fitness = bestFitness; return(bestFitness); }
public void Correct() { for (int i = 0; i < GenesLength; i++) { var move = new TMove(); move.Decode((int)Genes[i]); for (int j = i - 1; j >= 0; j--) { var pMove = new TMove(); pMove.Decode((int)Genes[j]); if (move.Axis != pMove.Axis) { break; } if (move.SegNo == pMove.SegNo) { RemoveGene(i); i--; var angle = (pMove.Angle + move.Angle + 2) % 4; if (angle == 0) { RemoveGene(j); i--; } else { pMove.Angle = angle - 1; Genes[j] = pMove.Encode(); } break; } } } }
void Solve() { var best = new RubikGenome(); best.Fitness = HighScore; foreach (var solution in Solutions) { var genome = new RubikGenome(); var cube = new RubikCube(RubikCube); for (int i = 0; i < solution.Value.Count; i++) { var move = solution.Value[i]; cube.MakeMove(move); genome.Genes[i] = move.Encode(); } genome.Fitness = cube.Evaluate(); if (genome.Fitness < best.Fitness) { best = genome; } } if (best.Fitness >= HighScore) { TChromosome.GenesLength = 30; TChromosome.MinGenes = new double[TChromosome.GenesLength]; TChromosome.MaxGenes = new double[TChromosome.GenesLength]; for (int i = 0; i < TChromosome.MaxGenes.Length; i++) { TChromosome.MaxGenes[i] = 9 * RubikCube.N; } TGA <RubikGenome> .GenerationsCount = 50; TGA <RubikGenome> .MutationRatio = 0.2; TGA <RubikGenome> .WinnerRatio = 0.1; var ga = new TGA <RubikGenome>(); ga.Evaluate = OnEvaluate; ga.Progress = OnProgress; ga.Execute(); best = ga.Best; if (best.Fitness == 0) { SaveSolution(best); } } if (best.Fitness < HighScore) { Moves.Clear(); for (int i = 0; i < best.MovesCount; i++) { var move = new TMove(); move.Decode((int)best.Genes[i]); Moves.Add(move); } HighScore = best.Fitness; } MoveTimer.Start(); }