Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Problems.GrammaticalOptimization/Problems/HardPalindromeProblem.cs @ 11857

Last change on this file since 11857 was 11857, checked in by gkronber, 9 years ago

#2283: solution reorg

File size: 2.2 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
6
7namespace HeuristicLab.Problems.GrammaticalOptimization {
8  public class HardPalindromeProblem : ISymbolicExpressionTreeProblem {
9    // length of the longest palindrome in the sentence + number of different symbols occurring in the palindrome
10    private const string grammarString = @"
11G(S):
12S -> T | TS
13T -> a .. z
14";
15    private const string hlGrammarString = @"
16G(S):
17S -> a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z | SS
18";
19
20    private readonly IGrammar grammar;
21    public HardPalindromeProblem() {
22      this.grammar = new Grammar(grammarString);
23      this.TreeBasedGPGrammar = new Grammar(hlGrammarString);
24    }
25
26    public double BestKnownQuality(int maxLen) {
27      // the whole sentence is a palindrome + each symbol occurs only once or twice
28      // for odd total length the number of different characters can be larger than len/2 (aba)
29      // the second part is limited to 26 different characters
30      return maxLen + Math.Min(26, (maxLen + 1) / 2);
31    }
32
33    public IGrammar Grammar {
34      get { return grammar; }
35    }
36
37    public double Evaluate(string sentence) {
38      var palindrome = PalindromeProblem.LongestPalindromicSubstring(sentence);
39      var palindromeBytes = ASCIIEncoding.ASCII.GetBytes(palindrome);
40      var chrCount = new int[256];
41      foreach (var b in palindromeBytes) {
42        chrCount[b]++;
43      }
44      return palindrome.Length + chrCount.Count(c => c > 0);
45    }
46
47    public string CanonicalRepresentation(string phrase) {
48      return phrase;
49    }
50
51    public IEnumerable<Feature> GetFeatures(string phrase)
52    {
53      throw new NotImplementedException();
54    }
55
56    public IGrammar TreeBasedGPGrammar { get; private set; }
57    public string ConvertTreeToSentence(ISymbolicExpressionTree tree) {
58      var sb = new StringBuilder();
59      foreach (var s in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix()) {
60        if (s.Symbol.Name == "S") continue;
61        sb.Append(s.Symbol.Name);
62      }
63      return sb.ToString();
64    }
65  }
66}
Note: See TracBrowser for help on using the repository browser.