Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2886_SymRegGrammarEnumeration/HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration/GrammarEnumeration/Sentence.cs @ 15928

Last change on this file since 15928 was 15827, checked in by lkammere, 7 years ago

#2886: Change implementation of symbol strings from list to array.

File size: 2.3 KB
Line 
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Diagnostics;
5using System.Linq;
6
7namespace HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration.GrammarEnumeration {
8  public class SymbolString : IEnumerable<Symbol> {
9    private readonly Symbol[] symbols;
10
11    public Symbol this[int index] {
12      get { return symbols[index]; }
13    }
14
15    public SymbolString(IEnumerable<Symbol> s) {
16      symbols = s.ToArray();
17    }
18
19    public SymbolString(params Symbol[] s) {
20      symbols = s;
21    }
22
23    public bool IsSentence() {
24      return !this.Any(sym => sym is NonterminalSymbol);
25    }
26
27    public int[] GetNonterminalSymbolIndexes() {
28      return Enumerable.Range(0, symbols.Length)
29        .Where(i => symbols[i] is NonterminalSymbol)
30        .ToArray();
31    }
32
33    public int NextNonterminalIndex() {
34      Debug.Assert(!IsSentence());
35      int firstNonTerminalIndex = 0;
36      while (firstNonTerminalIndex < symbols.Length && symbols[firstNonTerminalIndex] is TerminalSymbol) {
37        firstNonTerminalIndex++;
38      }
39      return firstNonTerminalIndex;
40    }
41
42    public SymbolString DerivePhrase(int nonterminalSymbolIndex, Production production) {
43      int productionLength = production.Count;
44      int newStringLength = Count() + productionLength - 1;
45      Symbol[] newPhrase = new Symbol[newStringLength];
46
47      // Copy "left" part of the phrase
48      Array.Copy(symbols, 0, newPhrase, 0, nonterminalSymbolIndex);
49      // Copy production and overwrite nonterminalsymbol
50      production.CopyTo(0, newPhrase, nonterminalSymbolIndex, productionLength);
51      // Copy "right" part of the original phrase
52      Array.Copy(symbols, nonterminalSymbolIndex + 1, newPhrase, nonterminalSymbolIndex + productionLength, symbols.Length - nonterminalSymbolIndex - 1);
53
54      return new SymbolString(newPhrase);
55    }
56
57    public override string ToString() {
58      return string.Join<Symbol>(" ", symbols);
59    }
60
61    #region Enumerable interface
62    IEnumerator IEnumerable.GetEnumerator() {
63      return GetEnumerator();
64    }
65
66    public IEnumerator<Symbol> GetEnumerator() {
67      return ((IEnumerable<Symbol>)symbols).GetEnumerator();
68    }
69
70    public int Count() {
71      return symbols.Length;
72    }
73    #endregion
74  }
75}
Note: See TracBrowser for help on using the repository browser.