Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Problems.GrammaticalOptimization/Problems/HardPalindromeProblem.cs @ 12295

Last change on this file since 12295 was 12099, checked in by gkronber, 10 years ago

#2283: name for all problems (for output), new unit test, and added testsettings file

File size: 2.3 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 string Name { get { return "HardPalindrome"; } }
22
23    public HardPalindromeProblem() {
24      this.grammar = new Grammar(grammarString);
25      this.TreeBasedGPGrammar = new Grammar(hlGrammarString);
26    }
27
28    public double BestKnownQuality(int maxLen) {
29      // the whole sentence is a palindrome + each symbol occurs only once or twice
30      // for odd total length the number of different characters can be larger than len/2 (aba)
31      // the second part is limited to 26 different characters
32      return maxLen + Math.Min(26, (maxLen + 1) / 2);
33    }
34
35    public IGrammar Grammar {
36      get { return grammar; }
37    }
38
39    public double Evaluate(string sentence) {
40      var palindrome = PalindromeProblem.LongestPalindromicSubstring(sentence);
41      var palindromeBytes = ASCIIEncoding.ASCII.GetBytes(palindrome);
42      var chrCount = new int[256];
43      foreach (var b in palindromeBytes) {
44        chrCount[b]++;
45      }
46      return palindrome.Length + chrCount.Count(c => c > 0);
47    }
48
49    public string CanonicalRepresentation(string phrase) {
50      return phrase;
51    }
52
53    public IEnumerable<Feature> GetFeatures(string phrase)
54    {
55      throw new NotImplementedException();
56    }
57
58    public IGrammar TreeBasedGPGrammar { get; private set; }
59    public string ConvertTreeToSentence(ISymbolicExpressionTree tree) {
60      var sb = new StringBuilder();
61      foreach (var s in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix()) {
62        if (s.Symbol.Name == "S") continue;
63        sb.Append(s.Symbol.Name);
64      }
65      return sb.ToString();
66    }
67  }
68}
Note: See TracBrowser for help on using the repository browser.