Advertisement
kot025

Markov2.0

Feb 22nd, 2015
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.50 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 Markov2
  8. {
  9.     class Program
  10.     {
  11.         static string s; // тут хранится строка глобально
  12.         static string a; // здесь алфавит
  13.         static string[] left; // массив левых частей введенных правил
  14.         static string[] right; // массив правых частей
  15.         static bool[] end; // массив тру-фолс в зависимости от конечности или не конечности мета-символа в правиле соотв.
  16.  
  17.         static void RedLn(string str) // Console.WriteLine красного цвета
  18.         {
  19.             Console.ForegroundColor = ConsoleColor.Red;
  20.             Console.WriteLine(str);
  21.             Console.ResetColor();
  22.         }
  23.         static void WhiteLn(string str) // Console.WriteLine белого цвета
  24.         {
  25.             Console.ForegroundColor = ConsoleColor.White;
  26.             Console.WriteLine(str);
  27.             Console.ResetColor();
  28.         }
  29.  
  30.         static int AskForAction(int qtyOfActions) // запрос команды меню и проверка вводимых значений
  31.         {
  32.             int act;
  33.             bool ok;
  34.             do
  35.             {
  36.                 Console.Write("Команда: ");
  37.                 string buf = Console.ReadLine();
  38.                 ok = int.TryParse(buf, out act) && act > 0 && act <= qtyOfActions;
  39.                 if (!ok)
  40.                     RedLn("Доступны команды 1 - " + qtyOfActions + ".");
  41.             } while (!ok);
  42.             return act;
  43.         }
  44.         static string RemoveSpaces(string s)
  45.         {
  46.             s = s.Replace(" ", string.Empty);
  47.             s = s.Trim().Replace(" ", string.Empty);
  48.             return s;
  49.         }
  50.         static bool FindEquals(string sString)
  51.         {
  52.             bool ok = false;
  53.             char[] sChar = new char[sString.Length];
  54.             sChar = sString.ToCharArray();
  55.             for (int i = 0; i < sChar.Length; i++)
  56.             {
  57.                 if (i != 0)
  58.                 {
  59.                     for (int j = 0; j < i; j++)
  60.                     {
  61.                         if (sChar[j] == sChar[i])
  62.                         {
  63.                             ok = true;
  64.                             break;
  65.                         }
  66.                     }
  67.                 }
  68.                 if ((i != sChar.Length) && (ok != true))
  69.                 {
  70.                     for (int j = i + 1; j < sChar.Length; j++)
  71.                     {
  72.                         if (sChar[j] == sChar[i])
  73.                         {
  74.                             ok = true;
  75.                             break;
  76.                         }
  77.                     }
  78.                 }
  79.                 if (ok == true)
  80.                 {
  81.                     break;
  82.                 }
  83.             }
  84.             return ok;
  85.         }
  86.         static bool Alf(string s) // проверка на соответствие алфавиту
  87.         {
  88.             bool ok = true;
  89.             for (int i = 0; i < s.Length; i++)
  90.             {
  91.                 if (!a.Contains(s[i]))
  92.                 {
  93.                     ok = false;
  94.                     break;
  95.                 }
  96.             }
  97.             return ok;
  98.         }
  99.  
  100.         static int Check(string rule) // проверка на наличие в строке мета-символа и на его положение, возврат кода ошибки
  101.         {
  102.             int code = 0;
  103.             if (rule.Contains("->"))
  104.             {
  105.                 if (rule.IndexOf("->") == 0)
  106.                 {
  107.                     code = 2;
  108.                 }
  109.             }
  110.             else
  111.             {
  112.                 code = 1;
  113.             }
  114.             return code;
  115.         }
  116.         static int Split(string rule, int i) // проверяем левую-правую части переданной строки правила с переданным номером
  117.         {                               // и записываем куски правила в соотв. массивы под соотв. номерами
  118.             int index = -1;
  119.             index = rule.IndexOf("->.");
  120.             if (index == -1)
  121.             {
  122.                 index = rule.IndexOf("->");
  123.             }
  124.             if (!Alf(rule.Substring(0, index)))
  125.             {
  126.                 return 1;  // левая часть правила не соотв. алф.
  127.             }
  128.             left[i] = rule.Substring(0, index);
  129.             if ((index + 2) == rule.Length)
  130.             {
  131.                 end[i] = false;
  132.                 right[i] = null;
  133.                 return 0;
  134.             }
  135.             else
  136.             {
  137.                 if (((index + 3) == rule.Length) && (rule[index + 2] == '.'))
  138.                 {
  139.                     end[i] = true;
  140.                     right[i] = null;
  141.                     return 0;
  142.                 }
  143.                 else
  144.                 {
  145.                     if (rule[index + 2] == '.')
  146.                     {
  147.                         if (!Alf(rule.Substring(index + 3, rule.Length - index - 3))) // правая часть правила с "->." не соотв. алф.
  148.                         {
  149.                             return 2;
  150.                         }
  151.                         else
  152.                         {
  153.                             end[i] = true;
  154.                             right[i] = rule.Substring(index + 3, rule.Length - index - 3);
  155.                             return 0;
  156.                         }
  157.                     }
  158.                     else
  159.                     {
  160.                         if (!Alf(rule.Substring(index + 3, rule.Length - index - 3))) // правая часть правила c "->" не соотв. алф.
  161.                         {
  162.                             return 2;
  163.                         }
  164.                         else
  165.                         {
  166.                             end[i] = false;
  167.                             right[i] = rule.Substring(index + 2, rule.Length - index - 2);
  168.                             return 0;
  169.                         }
  170.                     }
  171.                 }
  172.             }
  173.         }
  174.  
  175.         static void WorkAlphabet(ref bool alfin)
  176.         {
  177.             string a1;
  178.             int act;
  179.             Console.Clear();
  180.             if (alfin) // если алфавит уже введен
  181.             {
  182.                 Console.Write("Aлфавит: ");
  183.                 WhiteLn(a);
  184.                 Console.WriteLine();
  185.                 Console.WriteLine("1. Ввести новый алфавит\n2. Добавить символы в имеющийся");
  186.                 act = AskForAction(2);
  187.                 if (act == 1)
  188.                 {
  189.                     do
  190.                     {
  191.                         Console.Write("Введите алфавит в одну строку:");
  192.                         a1 = Console.ReadLine();
  193.                         a1 = RemoveSpaces(a1);
  194.                         if (FindEquals(a1) == true)
  195.                         {
  196.                             RedLn("Ошибка. В вашем алфавите найдены повторяющиеся элементы. Повторите ввод.\n");
  197.                         }
  198.                     }
  199.                     while (FindEquals(a1) == true);
  200.                     a = a1 + " ";
  201.                 }
  202.                 else
  203.                 {
  204.                     // запросить новую строку, проверить на повторы внутри самой себя
  205.                     // проверить на одинаковые символы старый алфавит и новый кусок
  206.                     // если все ок - добавить ее в конец имеющегося алфавита
  207.                 }
  208.             }
  209.             else // если алфавита не было
  210.             {
  211.                 do
  212.                 {
  213.                     Console.Write("Введите алфавит в одну строку:");
  214.                     a1 = Console.ReadLine();
  215.                     a1 = RemoveSpaces(a1);
  216.                     if (FindEquals(a1) == true)
  217.                     {
  218.                         RedLn("Ошибка. В вашем алфавите найдены повторяющиеся элементы. Повторите ввод.\n");
  219.                     }
  220.                 }
  221.                 while (FindEquals(a1) == true);
  222.                 a = a1 + " ";
  223.                 alfin = true;
  224.             }
  225.         } // работа с алфавитом
  226.         static void InputNewRule(/* сюда можно передать номер, на который мы вводим новые правило*/)
  227.         {
  228.             // запрашиваем ввод нового правила, проверяем всяко-разно, дописываем в массивы
  229.         }
  230.         static void WorkRules(ref bool rulin) // работа с правилами
  231.         {
  232.             Console.Clear();
  233.             if (rulin)
  234.             {
  235.                 // заменить (заменить старые на новые выборочно) или добавить новые (заменить пустое (n+1)-е правило на новое k раз, где n - номер максимального введенного правила)
  236.                 // если заменить - спрашивает у пользователя номера заменяемых правил, вызывает InputNewRules для всех нужных номеров
  237.                 // если ввести новые - вызывает InputNewRules, передавая ей в качестве номера вводимого правила номер, превышающий  на 1. потом спрашивает - ввести ли еще
  238.             }
  239.             else
  240.             {
  241.                 // вызывает InputNewRules, передавая ей в качестве номера вводимого правила номер, превышающий номер максимального введенного правила на 1. потом спрашивает - ввести ли еще
  242.             }
  243.            
  244.         }
  245.         static void Main(string[] args)
  246.         {
  247.             //bool alfin = true; a = "стрк-алфовит";
  248.             bool alfin = false;
  249.  
  250.             //bool strin = true; s = "строка-строка";
  251.             bool strin = false;
  252.  
  253.             //bool rulin = true;
  254.             bool rulin = false;
  255.  
  256.             int act = 0;
  257.             right = null;
  258.             end = null;
  259.             left = null;
  260.             int ruleNumber = 0;
  261.             int exit;
  262.             Console.Clear();
  263.             //Console.WriteLine("Нормальные алгорифмы Маркова.\n\nДля продолжения нажмите любую клавишу");
  264.             //Console.ReadKey();
  265.            
  266.             do
  267.             {
  268.                 Console.Clear();
  269.                 if (alfin)
  270.                 {
  271.                     Console.Write("Алфавит: ");
  272.                     WhiteLn(a);
  273.                 }
  274.                 if (strin)
  275.                 {
  276.                     Console.Write("Строка: ");
  277.                     WhiteLn(s);
  278.                 }
  279.                 if (rulin)
  280.                 {
  281.                    
  282.                 }
  283.                 if (alfin || strin || rulin)
  284.                 {
  285.                     Console.WriteLine();
  286.                 }
  287.                 int menuCounter = 0;
  288.  
  289.                 if (!alfin)
  290.                 {
  291.                     Console.WriteLine(++menuCounter + ". Ввести новый алфавит");
  292.                 }
  293.                 else
  294.                 {
  295.                     Console.WriteLine(++menuCounter + ". Работа с алфавитом");
  296.                     if (!strin)
  297.                     {
  298.                         Console.WriteLine(++menuCounter + ". Ввести новую строку");
  299.                     }
  300.                    
  301.                     else
  302.                     {
  303.                         Console.WriteLine(++menuCounter + ". Работа со строкой");
  304.                         if (!rulin)
  305.                         {
  306.                             Console.WriteLine(++menuCounter + ". Ввести новые правила");
  307.                         }
  308.                         else
  309.                         {
  310.                             Console.WriteLine(++menuCounter + ". Работа с правилами");
  311.  
  312.                             Console.WriteLine("\n" + ++menuCounter + ". Обработать строку");
  313.                         }
  314.                     }
  315.                 }
  316.  
  317.                 Console.WriteLine("\n" + ++menuCounter + ". Выход"); exit = menuCounter;
  318.                 Console.WriteLine();
  319.  
  320.                 act = AskForAction(exit);
  321.                 switch (act)
  322.                 {
  323.                     case 1:
  324.                         WorkAlphabet(ref alfin);
  325.                         break;
  326.                     case 2:
  327.                         if (act != exit)
  328.                         {
  329.                             Console.Clear();
  330.                             Console.Write("Алфавит: ");
  331.                             WhiteLn(a);
  332.                             Console.WriteLine();
  333.                             bool ok;
  334.                             do
  335.                             {
  336.                                 Console.Write("Введите строку для работы: ");
  337.                                 s = Console.ReadLine();
  338.                                 ok = Alf(s);
  339.                                 if (!ok)
  340.                                 {
  341.                                     RedLn("Ошибка. В строке обнаружены недопустимые символы.\n");
  342.                                 }
  343.                             } while (!ok);
  344.                             strin = true;
  345.                         }
  346.                         break;
  347.                     case 3:
  348.                         if (act != exit)
  349.                         {
  350.                             //WorkRules();  здесь остановился
  351.                         }
  352.                         break;
  353.                 }
  354.  
  355.             } while (act != exit);
  356.  
  357.         }
  358.     }
  359. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement