public void Hello_World() { const string genes = @"`1234567890-=~!@#$%^&*()_+qwertyuiop[]\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:""zxcvbnm,./ZXCVBNM<>? "; string target = "Hello world!"; Func<string, FitnessResult> calcFitness = str => { uint fitness = 0; for (int j = 0; j < target.Length; j++) { try { fitness += str[j] == target[j] ? 0U : 1; } catch (Exception e) { Console.WriteLine(e); throw; } } return new FitnessResult { Value = fitness }; }; var best = new GeneticSolver().GetBestGenetically(target.Length, genes, calcFitness); Console.WriteLine(best.Genes); }
private static void GenerateRegex(IEnumerable<string> target, IEnumerable<string> dontMatch, int expectedLength) { string distinctSymbols = new String(target.SelectMany(x => x).Distinct().ToArray()); string genes = distinctSymbols + "?*()[^]+"; Func<string, FitnessResult> calcFitness = str => { if (!IsValidRegex(str)) { return new FitnessResult { Value = Int32.MaxValue }; } var regex = new Regex("^" + str + "$"); uint fitness = target.Aggregate<string, uint>(0, (current, t) => current + (regex.IsMatch(t) ? 0U : 1)); uint nonFitness = dontMatch.Aggregate<string, uint>(0, (current, t) => current + (regex.IsMatch(t) ? 10U : 0)); return new FitnessResult { Value = fitness + nonFitness }; }; int targetGeneLength = 1; for (;;) { var best = new GeneticSolver(50 + 10 * targetGeneLength).GetBestGenetically(targetGeneLength, genes, calcFitness); if (calcFitness(best.GetStringGenes()).Value != 0) { Console.WriteLine("-- not solved with regex of length " + targetGeneLength); targetGeneLength++; if (targetGeneLength > expectedLength) { Assert.Fail("failed to find a solution within the expected length"); } continue; } Console.WriteLine("solved with: " + best); break; } }
private static void FindBest(int numberOfCharacters, int expectedLength) { Func<string, FitnessResult> calcFitness = x => { string result = Run(x); return new FitnessResult { Value = (uint)(expectedLength * 2 - result.Length) }; }; var geneticSolver = new GeneticSolver(300) { UseFastSearch = true }; var best = geneticSolver.GetBestGenetically(numberOfCharacters, "ASCP", calcFitness); string finalString = Run(best.Genes); Console.WriteLine(best + " generatates final string with length " + finalString.Length); finalString.Length.ShouldBeGreaterThanOrEqualTo((int)(.8m*expectedLength)); }