Advertisement
marcelsmudda

ContainsWordGrammar

Jul 26th, 2014
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.01 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ContainsWord
  8. {
  9.     class Grammar
  10.     {
  11.         public string[] Variables { get; private set; }
  12.         public char[] Terminals { get; private set; }
  13.         public Rule[] Rules { get; private set; }
  14.         public string StartSymbol { get; private set; }
  15.  
  16.         public Grammar(string variables, string terminals, string rules, string start)
  17.         {
  18.             Variables = variables.Substring(1, variables.Length - 2).Split(',');
  19.             Terminals = Array.ConvertAll(terminals.Substring(1, terminals.Length - 2).Split(','), s => s[0]);
  20.             Rules = Rule.Create(rules.Substring(1, rules.Length - 2).Split(','));
  21.             StartSymbol = start;
  22.         }
  23.     }
  24.  
  25.     class Rule
  26.     {
  27.         public static Rule[] Create(string[] rules)
  28.         {
  29.             var arr = new Rule[rules.Length];
  30.             for (var i = 0; i < rules.Length; i++)
  31.             {
  32.                 arr[i] = new Rule(rules[i]);
  33.             }
  34.             return arr;
  35.         }
  36.  
  37.         public string Input { get; private set; }
  38.         public string Output { get; private set; }
  39.  
  40.         private Rule(string rule)
  41.         {
  42.             var parts = rule.Split(new string[] { "->" }, StringSplitOptions.None);
  43.             Input = parts[0];
  44.             Output = parts[1];
  45.         }
  46.  
  47.         public void Use(string form, List<string> set, string target)
  48.         {
  49.             var matches = System.Text.RegularExpressions.Regex.Matches(form, Input);
  50.             foreach (System.Text.RegularExpressions.Match match in matches)
  51.             {
  52.                 var result = match.Index + 1 < form.Length ? form.Substring(0, match.Index) + Output + form.Substring(match.Index + Input.Length) :
  53.                     form.Substring(0, match.Index) + Output;
  54.                 if (result.Length <= target.Length && !set.Contains(result))
  55.                     set.Add(result);
  56.             }
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement