using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; namespace HeuristicLab.Problems.GrammaticalOptimization { public class PermutationProblem : ISymbolicExpressionTreeProblem { private const string grammarString = @" G(S): S -> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f | 0S | 1S | 2S | 3S | 4S | 5S | 6S | 7S | 8S | 9S | aS | bS | cS | dS | eS | fS "; private const string hlGrammarString = @" G(S): S -> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f | SS "; private readonly IGrammar grammar; public PermutationProblem() { this.grammar = new Grammar(grammarString); this.TreeBasedGPGrammar = new Grammar(hlGrammarString); } public double BestKnownQuality(int maxLen) { return Math.Min(16.0, maxLen); } public IGrammar Grammar { get { return grammar; } } public double Evaluate(string sentence) { // sentence must contain only terminal symbols, we are not checking if the sentence is syntactically valid here because it would be too slow! Debug.Assert(sentence.Any(c => grammar.IsTerminal(c))); return sentence.Distinct().Count(); } public string CanonicalRepresentation(string phrase) { return phrase; } public IEnumerable GetFeatures(string phrase) { throw new NotImplementedException(); } public IGrammar TreeBasedGPGrammar { get; private set; } public string ConvertTreeToSentence(ISymbolicExpressionTree tree) { var sb = new StringBuilder(); foreach (var s in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix()) { if (s.Symbol.Name == "S") continue; sb.Append(s.Symbol.Name); } return sb.ToString(); } } }