Advertisement
Guest User

Untitled

a guest
Feb 25th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.04 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. using System.IO;
  7.  
  8. namespace Интерпретатор_НАМ
  9. {
  10. class Program
  11. {
  12. public struct Rules
  13. {
  14. public string word;//для записи символов
  15. public string pravilo;//для записи правил для символов
  16. public bool last;//для определения конечности операции
  17. }
  18. public static void Print(char[] mas1, int count)
  19. {
  20. int i = 0;
  21. Console.WriteLine("Исходный алвавит: ");
  22. for (i = 0; i < count; i++) Console.Write(mas1[i] + " ");
  23. Console.WriteLine();
  24. }
  25. public static void Print(Rules[] rules)
  26. {
  27. int i = 0;
  28. Console.WriteLine("Набор правил: ");
  29. for (i = 0; i < rules.Length; i++)
  30. {
  31. if (rules[i].last) Console.WriteLine("{0}->.{1}", rules[i].word, rules[i].pravilo);
  32. else Console.WriteLine("{0}->{1}", rules[i].word, rules[i].pravilo);
  33. }
  34. Console.WriteLine();
  35. }
  36. public static char[] Alphabet(ref int count)
  37. {
  38. char[] mas = new char[100];
  39. string s;
  40. bool right = false;
  41. char s1 = ' ';
  42. count = 0;
  43. Console.WriteLine(@"Вводите символы алфавита последовательно!
  44. Обратите внимание, что алфавит может содержать только маленькие латинские буквы, цифры, знаки (*, %, &, #, $, /, +, -) и знак пустоты Л (лямбда).
  45. Если вы хотите использовать пустоту в правилах, запишите её в ваш алфавит.
  46. Если вы хотите прервать процесс ввода правил, введите '!'.
  47. ");
  48. do
  49. {
  50. do
  51. {
  52. Console.Write("Введите {0} символ алфавита: ", count + 1);
  53. s = Console.ReadLine();
  54. if (s == "!") break;
  55. else
  56. {
  57. s = s.Trim();
  58. if (s == "") { Console.WriteLine("Строка пуста! Введите символ!"); right = false; }
  59. else if (s.Length > 1) { Console.WriteLine("Символ алфавита должен содержать не более одного символа! Повторите ввод."); right = false; }
  60. else
  61. {
  62. s1 = Convert.ToChar(s);
  63. if ((s1 >= 'a') && (s1 <= 'z') || (s1 >= '0') && (s1 <= '9') || (s1 == '*') || (s1 == 'Л') || (s1 == '#') || (s1 == '&') || (s1 == '%') || (s1 == '/') || (s1 == '$') || (s1 == '+') || (s1 == '-')) right = true;
  64. else { Console.WriteLine("Неверный символ! Повторите ввод."); right = false; }
  65. }
  66. if (right)
  67. {
  68. for (int i = 0; i < count; i++)
  69. {
  70. if (mas[i] == s1) { Console.WriteLine("Такой символ уже существует в алфавите! Повторите ввод."); right = false; break; }
  71. }
  72. }
  73. if (right)
  74. {
  75. mas[count] = s1;
  76. count++;
  77. }
  78. else break;
  79. }
  80. } while (count == 0);
  81. if (count == 45) Console.WriteLine("Вы ввели максимально допустимое число символов!");
  82. if (count == 0) Console.WriteLine("Вы не ввели ни одного символа алфавита!");
  83. if (s == "!" && count != 0) break;
  84. } while (count < 45);
  85. char[] mas1 = new char[count + 3];
  86. for (int i = 0; i < count; i++) mas1[i] = mas[i];
  87. mas1[count] = '>'; mas1[count + 1] = '-'; mas1[count + 2] = '.';
  88. return mas1;
  89. }
  90. public static bool Check(ref string str, char[] mas)//проверка ввода строки, а также правил
  91. {
  92. bool right = false;//для проверки строки
  93. int pustota = 0, mestopusto = 0;//для проверки наличия пустоты
  94. str = str.Trim();
  95. for (int i = 0; i < str.Length; i++)
  96. if (str[i] == ' ')
  97. {
  98. str = str.Remove(i, 1);
  99. i--;
  100. }
  101. //Console.WriteLine(str);
  102. char[] arr = str.ToCharArray();
  103. for (int i = 0; i < arr.Length; i++)
  104. {
  105. right = false;
  106. for (int j = 0; j < mas.Length; j++)
  107. {
  108. if (arr[i] == mas[j]) right = true;
  109. }
  110. if (arr[i] == 'Л') { pustota++; mestopusto = i; }
  111. if (!right) { Console.WriteLine("Ошибка в введенной строке: несоответствие введенных символов алфавиту! Повторите ввод."); break; }
  112. }
  113. if (right && pustota != 0)
  114. {
  115. //Console.WriteLine(pustota);
  116. if (pustota > 1) { right = false; Console.WriteLine("Ошибка со знаком пустоты! Повторите ввод."); }
  117. else
  118. {
  119. //Console.WriteLine(mestopusto);
  120. if (mestopusto == 0 && str[mestopusto + 1] == '-' || mestopusto == (str.Length - 1) && ((str[mestopusto - 1] == '>' || str[mestopusto - 1] == '.'))) right = true;
  121. else { right = false; Console.WriteLine("Ошибка с постановкой знака пустоты! Повторите ввод."); }
  122. }
  123. }
  124. if (!right) return false;
  125. else return true;
  126. }
  127. public static Rules[] Rule(char[] mas)
  128. {
  129. bool right, last = false, end = false;
  130. string str;
  131. int i = 0, j = 0, num = 0, count = 0, count1 = 0;
  132. string word1, pravilo1;
  133. Rules[] rules = new Rules[100];
  134. Console.WriteLine(@"Вводите комбинации символов и правила для них:
  135. через знак '->' , если правило не должно быть конечным;
  136. через знак '->.' , если правило конечное.
  137. Максимальное количество правил: 100.
  138. Максимальное количество шагов: 5000.
  139. Если вы хотите прервать процесс ввода правил, введите '!'.");
  140. do
  141. {
  142. do
  143. {
  144. count = 0;
  145. Console.WriteLine("Введите правило " + (num + 1) + ":");
  146. str = Console.ReadLine();
  147. if (str == "!") break;
  148. right = false;
  149. end = false;
  150. right = Check(ref str, mas);
  151. if (right)
  152. {
  153. for (i = 0; i < str.Length; i++)
  154. {
  155. if (str[i] == '-')
  156. {
  157. if (str.Length == i + 1) { end = false; break; }
  158. if (str.Length > (i + 3) && str[i + 1] == '>' && str[i + 2] == '.') { last = true; end = true; break; }
  159. if (str.Length > (i + 2) && str[i + 1] == '>') { last = false; end = true; break; }
  160. break;
  161. }
  162. }
  163. if (end && (str[str.Length - 1] == '>' || str[str.Length - 1] == '.')) { right = false; Console.WriteLine("Отсутствует правая часть правила!"); }
  164. if (!end && (str[str.Length - 1] == '.' || str[str.Length - 1] == '>')) { right = false; Console.WriteLine("Отсутствует правая часть правила!"); }
  165. else if (!end) { Console.WriteLine("Отсутствует символ '->' или '->.'!"); right = false; }
  166. if (i == 0) { right = false; Console.WriteLine("Отсутствует левая часть правила!"); }
  167. }
  168. if (right)
  169. {
  170. char[] brr = str.ToCharArray();
  171. if (last)
  172. {
  173. count = 0;
  174. j = 0;
  175. while (brr[count] != '-') count++;
  176. char[] word = new char[count];
  177. count1 = (brr.Length - count) - 3;
  178. char[] pravilo = new char[count1];
  179. for (i = 0; i < word.Length; i++) word[i] = brr[i];
  180. for (i = count + 3; i < brr.Length; i++) { pravilo[j] = brr[i]; j++; }
  181. word1 = new string(word);
  182. pravilo1 = new string(pravilo);
  183. for (i = 0; i < num; i++) if (rules[i].word == word1) { right = false; Console.WriteLine("Этому слову уже присвоено правило!"); }
  184. if (right)
  185. {
  186. rules[num].word = word1;
  187. rules[num].pravilo = pravilo1;
  188. //Console.WriteLine("Правило принимает следующий вид. Должно без точки "+rules[num].pravilo);
  189. rules[num].last = true;
  190. }
  191. }
  192. else
  193. {
  194. count = 0;
  195. j = 0;
  196. while (brr[count] != '-') count++;
  197. char[] word = new char[count];
  198. count1 = (brr.Length - count) - 2;
  199. char[] pravilo = new char[count1];
  200. for (i = 0; i < word.Length; i++) word[i] = brr[i];
  201. for (i = count + 2; i < brr.Length; i++) { pravilo[j] = brr[i]; j++; }
  202. word1 = new string(word);
  203. pravilo1 = new string(pravilo);
  204. for (i = 0; i < num; i++) if (rules[i].word == word1) { right = false; Console.WriteLine("Этому слову уже присвоено правило!"); }
  205. if (right)
  206. {
  207. rules[num].word = word1;
  208. rules[num].pravilo = pravilo1;
  209. rules[num].last = false;
  210. }
  211. }
  212. if (right) num++;
  213. }
  214. else break;
  215. } while (num == 0);
  216. if (num == 0) Console.WriteLine("Вы не ввели ни одного правила!");
  217. if (str == "!" && num != 0) break;
  218. if (num == rules.Length) Console.WriteLine("Вы ввели максимально возможное количество правил!");
  219. } while (num < rules.Length);
  220. Rules[] rules1 = new Rules[num];
  221. for (i = 0; i < rules1.Length; i++) rules1[i] = rules[i];
  222. return rules1;
  223. }
  224. public static Rules[] RulesFromFile(char[] mas)
  225. {
  226. int i = 0, j = 0, k, num = 0, count = 0, count1 = 0;
  227. bool ok, open, right = false, end = false, last = false;
  228. string name, str, word1, pravilo1;
  229. Rules[] rules = new Rules[100];
  230. do
  231. {
  232. try
  233. {
  234. Console.Write("Введите имя файла (без расширения): ");
  235. do
  236. {
  237. name = Convert.ToString(Console.ReadLine());
  238. ok = true;
  239. if (name.Length == 0)
  240. {
  241. ok = false;
  242. Console.WriteLine("Неверный ввод! Повторите попытку.");
  243. }
  244. } while (!ok);
  245. FileStream file = new FileStream(name + ".txt", FileMode.Open);
  246. StreamReader rd = new StreamReader(file);
  247. Rules[] rules1 = new Rules[100];
  248. for (k = 0; (str = rd.ReadLine()) != null && k < 100; k++)
  249. {
  250. count = 0;
  251. num = 0;
  252. count1 = 0;
  253. right = false;
  254. end = false;
  255. last = false;
  256. right = Check(ref str, mas);
  257. if (right)
  258. {
  259. for (i = 0; i < str.Length; i++)
  260. {
  261. if (str[i] == '-')
  262. {
  263. if (str.Length == i + 1) { end = false; break; }
  264. if (str.Length > (i + 3) && str[i + 1] == '>' && str[i + 2] == '.') { last = true; end = true; break; }
  265. if (str.Length > (i + 2) && str[i + 1] == '>') { last = false; end = true; break; }
  266. break;
  267. }
  268. }
  269. if (end && (str[str.Length - 1] == '>' || str[str.Length - 1] == '.')) right = false;
  270. if (!end && (str[str.Length - 1] == '.' || str[str.Length - 1] == '>')) right = false;
  271. else if (!end) right = false;
  272. if (i == 0) right = false;
  273. }
  274. if (right)
  275. {
  276. char[] brr = str.ToCharArray();
  277. if (last)
  278. {
  279. count = 0;
  280. j = 0;
  281. while (brr[count] != '-') count++;
  282. char[] word = new char[count];
  283. count1 = (brr.Length - count) - 3;
  284. char[] pravilo = new char[count1];
  285. for (i = 0; i < word.Length; i++) word[i] = brr[i];
  286. for (i = count + 3; i < brr.Length; i++) { pravilo[j] = brr[i]; j++; }
  287. word1 = new string(word);
  288. pravilo1 = new string(pravilo);
  289. for (i = 0; i < num; i++) if (rules[i].word == word1) right = false;
  290. if (right)
  291. {
  292. rules1[num].word = word1;
  293. rules1[num].pravilo = pravilo1;
  294. //Console.WriteLine("Правило принимает следующий вид. Должно без точки "+rules[num].pravilo);
  295. rules1[num].last = true;
  296. }
  297. }
  298. else
  299. {
  300. count = 0;
  301. j = 0;
  302. while (brr[count] != '-') count++;
  303. char[] word = new char[count];
  304. count1 = (brr.Length - count) - 2;
  305. char[] pravilo = new char[count1];
  306. for (i = 0; i < word.Length; i++) word[i] = brr[i];
  307. for (i = count + 2; i < brr.Length; i++) { pravilo[j] = brr[i]; j++; }
  308. word1 = new string(word);
  309. pravilo1 = new string(pravilo);
  310. for (i = 0; i < num; i++) if (rules[i].word == word1) right = false;
  311. if (right)
  312. {
  313. rules1[num].word = word1;
  314. rules1[num].pravilo = pravilo1;
  315. rules1[num].last = false;
  316. }
  317. }
  318. if (right) num++;
  319. }
  320. else break;
  321. }
  322. rd.Close();
  323. file.Close();
  324. open = true;
  325. Rules[] rules2 = new Rules[num];
  326. for (i = 0; i < rules2.Length; i++) rules2[i] = rules1[i];
  327. rules = rules2;
  328. if (right == false) { open = false; Console.WriteLine("При обработке правил из файла произошла ошибка! Выберите другой файл."); }
  329. if (k == 100) { open = false; Console.WriteLine("В данном файле более 100 правил! Выберите другой файл."); }
  330. }
  331. catch (IOException)
  332. {
  333. Console.WriteLine("\aОшибка открытия файла (возможно, файла не существует)!");
  334. open = false;
  335. }
  336. } while (!open);
  337. return rules;
  338. }
  339. static public void Markov(ref string s, Rules[] rules, ref int zachod, int results)
  340. {
  341. //i-для правил j-для строки
  342. int i = 0, j, k = 0, size = 0, z;
  343. bool found = false, end = false;
  344. do
  345. {
  346. for (i = 0; i < rules.Length; i++)
  347. {
  348. found = false;
  349. k = 0;
  350. //Console.WriteLine("Мы рассматриваем {0} ое правило", (i + 1));
  351. if (rules[i].word[0] == 'Л')
  352. {
  353. found = true;
  354. size = rules[i].pravilo.Length + s.Length;
  355. char[] arr = new char[size];
  356. while (k < rules[i].pravilo.Length) { arr[k] = rules[i].pravilo[k]; k++; }
  357. for (z = 0; z < s.Length; z++) { arr[k] = s[z]; k++; }
  358. s = new string(arr);
  359. if (rules[i].last) end = true;
  360. if (results == 1)
  361. {
  362. Console.WriteLine("После подстановки правила: " + s);
  363. Console.ReadLine();
  364. }
  365. i = -1;
  366. zachod++;
  367. }
  368. else
  369. {
  370. for (j = 0; j < s.Length; j++)
  371. {
  372. //Console.WriteLine("Длина строки" + s.Length);
  373. //Console.WriteLine("Первый символ правила " + rules[i].word[0]);
  374. //Console.WriteLine("Рассматриваемый сивол в строке " + s[j]);
  375. //Console.ReadLine();
  376. found = false;
  377. if (rules[i].word[0] == s[j])
  378. {
  379. //Console.WriteLine("Зашел в цикл. Символы оказались равны");
  380.  
  381. if (s.Length - j >= rules[i].word.Length)
  382. {
  383. int begin = j;
  384. for (z = 0; z < rules[i].word.Length; z++)
  385. {
  386. //Console.WriteLine("Зашёл в цикл for");
  387. if (s[begin] == rules[i].word[z]) { found = true; begin++; }
  388. else { found = false; break; }
  389. }
  390. }
  391. }
  392. if (found)
  393. {
  394. //Console.WriteLine("Место, с которого начнется замена " + (j + 1)); Console.WriteLine("Место, на котором замен азакончится " + (j + rules[i].word.Length));
  395. size = j + rules[i].pravilo.Length + (s.Length - (j + rules[i].word.Length));
  396. //Console.WriteLine("Мы заменим " + rules[i].word + " на " + rules[i].pravilo);
  397. //Console.WriteLine(size);
  398. if (rules[i].pravilo == "Л") size = size - 1;
  399. char[] arr = new char[size];
  400. while (k < j) { arr[k] = s[k]; k++; }
  401. if (rules[i].pravilo != "Л")
  402. for (z = 0; z < rules[i].pravilo.Length; z++) { arr[k] = rules[i].pravilo[z]; k++; }
  403. for (z = j + rules[i].word.Length; z < s.Length; z++) { arr[k] = s[z]; k++; }
  404. s = new string(arr);
  405. if (rules[i].last) end = true;
  406. if (results == 1)
  407. {
  408. Console.WriteLine("После {0} подстановки правила: {1}", zachod + 1, s);
  409. Console.ReadLine();
  410. }
  411. i = -1;
  412. zachod++;
  413. break;
  414. }
  415. }
  416. }//Console.WriteLine("Правило:" + i);
  417. if (i == rules.Length - 1 && found == false) { Console.WriteLine("Обойдя все правила, программа не нашла подходящего для продолжения обработки строки, поэтому выходим из цикла."); end = true; }
  418. if (zachod == 5000) end = true;
  419. if (end) break;
  420. }
  421. } while (!end);
  422. //Console.WriteLine(zachod);
  423. //Console.ReadLine();
  424. }
  425. public static bool CheckString(ref string s, int count, char[] mas)
  426. {
  427. bool right = false;
  428. for (int i = 0; i < s.Length; i++)
  429. if (s[i] == ' ')
  430. {
  431. s = s.Remove(i, 1);
  432. i--;
  433. }
  434. //Console.WriteLine(s);
  435. char[] arr = s.ToCharArray();
  436. for (int i = 0; i < arr.Length; i++)
  437. {
  438. right = false;
  439. for (int j = 0; j < count; j++)
  440. {
  441. if (arr[i] == mas[j]) right = true;
  442. }
  443. if (arr[i] == 'Л') right = false;
  444. if (!right) { Console.WriteLine("Ошибка в введенной строке!\nПроверьте правильность строки!"); break; }
  445. }
  446. if (right) return true;
  447. else return false;
  448. }
  449. public static int Menu(string sentence, ref int n)
  450. {
  451. bool Catch_Mist = false;
  452. Console.WriteLine(sentence);
  453. Console.WriteLine("1 - да\n2 - нет");
  454. do
  455. {
  456. Catch_Mist = int.TryParse(Console.ReadLine(), out n);
  457. if (!Catch_Mist) Console.WriteLine("Ошибка ввода! Повторите ввод.");
  458. if (Catch_Mist && (n > 2 || n < 1)) { Catch_Mist = false; Console.WriteLine("Ошибка ввода! Повторите ввод."); }
  459. } while (!Catch_Mist);
  460. return n;
  461. }
  462. static void Main(string[] args)
  463. {
  464. Console.Title = "Интерпретатор нормальных алгорифмов Маркова";
  465. Console.ForegroundColor = ConsoleColor.Yellow;
  466. Console.WriteLine("Вас приветствует программа \"Интерпретатор нормальных алгорифмов Маркова\"!");
  467. Console.WriteLine(@"Для лучшего отображения информации в окне советуем развернуть его на полный экран.
  468.  
  469. Обратите внимание:
  470. Максимальное количество символов (по количеству разрешенных для использования): 45.
  471. Максимальное количество правил: 100.
  472. Максимальное количество шагов: 5000.
  473.  
  474. Приятной работы!
  475. ");
  476. Console.ResetColor();
  477. bool right = false;
  478. int n = 0, zachod = 0, results = 0;
  479. string s;
  480. int count = 0;
  481. char[] mas;
  482. Rules[] rules = new Rules[100];
  483. do
  484. {
  485. do
  486. {
  487. mas = Alphabet(ref count);
  488. Print(mas, count);
  489. Menu("Хотите внести поправки в алфавит (ввести алфавит заново)?", ref n);
  490. } while (n == 1);
  491. Menu("Ввести правила из файла (в ином случае - ввод вручную)?", ref n);
  492. switch (n)
  493. {
  494. case 1:
  495. {
  496. rules = RulesFromFile(mas);
  497. Print(rules);
  498. break;
  499. }
  500. case 2:
  501. {
  502. do
  503. {
  504. rules = Rule(mas);
  505. Print(rules);
  506. Menu("Хотите внести поправки в правила (ввести правила заново)?", ref n);
  507. } while (n == 1);
  508. break;
  509. }
  510. }
  511. do
  512. {
  513. do
  514. {
  515. Console.WriteLine("Введите строку для обработки: ");
  516. s = Console.ReadLine();
  517. s = s.Trim();
  518. if (s == "") { Console.WriteLine("Строка пуста! Повторите ввод."); right = false; }
  519. else right = CheckString(ref s, count, mas);
  520. } while (!right);
  521. Menu("Хотите ли вы видеть промежуточные результаты?", ref results);
  522. Markov(ref s, rules, ref zachod, results);
  523. if (zachod == 5000) Console.WriteLine("Процесс зациклился или для его выполнения необходимо больше 5000 шагов.");
  524. else Console.WriteLine("Окончательный результат: " + s);
  525. zachod = 0;
  526. Menu("Хотите ввести другую строку для заданных правил?", ref n);
  527. } while (n == 1);
  528. Menu("Хотите поработать с другим алфавитом и правилами?", ref n);
  529. } while (n == 1);
  530. Console.ForegroundColor = ConsoleColor.Yellow;
  531. Console.WriteLine(@"Программа завершила свою работу.
  532. Спасибо, что воспользовались данным интерпретатором!
  533. Нажмите любую клавишу, чтобы закрыть окно...");
  534. Console.ResetColor();
  535. Console.ReadLine();
  536. }
  537. }
  538. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement