Line | |
---|
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 |
|
---|
8 | namespace HeuristicLab.Problems.GrammaticalOptimization {
|
---|
9 | // counts the number of times a pair of symbols occurs in a sentence
|
---|
10 | public class RoyalPairProblem : IProblem {
|
---|
11 | private const string grammarString = @"
|
---|
12 | G(S):
|
---|
13 | S -> a | aS | b | bS
|
---|
14 | ";
|
---|
15 |
|
---|
16 | private readonly IGrammar grammar;
|
---|
17 | public RoyalPairProblem() {
|
---|
18 | this.grammar = new Grammar(grammarString);
|
---|
19 | }
|
---|
20 |
|
---|
21 | public double BestKnownQuality(int maxLen) {
|
---|
22 | return maxLen - 1;
|
---|
23 | }
|
---|
24 |
|
---|
25 | public IGrammar Grammar {
|
---|
26 | get { return grammar; }
|
---|
27 | }
|
---|
28 |
|
---|
29 | private Regex regex = new Regex("(?=ab)|(?=ba)"); // count the number of "ab" and "ba" pairs
|
---|
30 | public double Evaluate(string sentence) {
|
---|
31 | // sentence must contain only terminal symbols, we are not checking if the sentence is syntactically valid here because it would be too slow!
|
---|
32 | Debug.Assert(sentence.Any(c => grammar.IsTerminal(c)));
|
---|
33 | return regex.Matches(sentence).Count;
|
---|
34 | }
|
---|
35 |
|
---|
36 | public string CanonicalRepresentation(string terminalPhrase) {
|
---|
37 | return terminalPhrase;
|
---|
38 | }
|
---|
39 | }
|
---|
40 | }
|
---|
Note: See
TracBrowser
for help on using the repository browser.