1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Diagnostics;
|
---|
4 | using System.Linq;
|
---|
5 | using System.Text;
|
---|
6 | using System.Text.RegularExpressions;
|
---|
7 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
8 |
|
---|
9 | namespace HeuristicLab.Problems.GrammaticalOptimization {
|
---|
10 | public class PermutationProblem : ISymbolicExpressionTreeProblem {
|
---|
11 | private const string grammarString = @"
|
---|
12 | G(S):
|
---|
13 | 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
|
---|
14 | ";
|
---|
15 |
|
---|
16 | private const string hlGrammarString = @"
|
---|
17 | G(S):
|
---|
18 | S -> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f | SS
|
---|
19 | ";
|
---|
20 |
|
---|
21 | private readonly IGrammar grammar;
|
---|
22 | public string Name { get { return "Permutation"; } }
|
---|
23 | public PermutationProblem() {
|
---|
24 | this.grammar = new Grammar(grammarString);
|
---|
25 | this.TreeBasedGPGrammar = new Grammar(hlGrammarString);
|
---|
26 | }
|
---|
27 |
|
---|
28 | public double BestKnownQuality(int maxLen) {
|
---|
29 | return Math.Min(16.0, maxLen);
|
---|
30 | }
|
---|
31 |
|
---|
32 | public IGrammar Grammar {
|
---|
33 | get { return grammar; }
|
---|
34 | }
|
---|
35 |
|
---|
36 | public double Evaluate(string sentence) {
|
---|
37 | // sentence must contain only terminal symbols, we are not checking if the sentence is syntactically valid here because it would be too slow!
|
---|
38 | Debug.Assert(sentence.Any(c => grammar.IsTerminal(c)));
|
---|
39 | return sentence.Distinct().Count();
|
---|
40 | }
|
---|
41 |
|
---|
42 | public string CanonicalRepresentation(string phrase) {
|
---|
43 | return phrase;
|
---|
44 | }
|
---|
45 |
|
---|
46 | public IEnumerable<Feature> GetFeatures(string phrase) {
|
---|
47 | throw new NotImplementedException();
|
---|
48 | }
|
---|
49 | public IGrammar TreeBasedGPGrammar { get; private set; }
|
---|
50 | public string ConvertTreeToSentence(ISymbolicExpressionTree tree) {
|
---|
51 | var sb = new StringBuilder();
|
---|
52 | foreach (var s in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix()) {
|
---|
53 | if (s.Symbol.Name == "S") continue;
|
---|
54 | sb.Append(s.Symbol.Name);
|
---|
55 | }
|
---|
56 | return sb.ToString();
|
---|
57 | }
|
---|
58 | }
|
---|
59 | }
|
---|