Advertisement
Guest User

Untitled

a guest
May 19th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 6.13 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <iostream>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <conio.h>
  6.  
  7. using namespace std;
  8.  
  9. int main(int argc, char *argv[]){
  10.  
  11. start:
  12.     system("CLS");
  13.     printf("Lab 9\n Graph algorithms. Streams\n Bershadskiy Andrew IS-81\n"); //меню
  14.     printf("---------------Options---------------\n");
  15.     printf("1. Read from text file\n");
  16.     printf("2. Exit\n");
  17.     printf("Choose your option: ");
  18.     int switcher = 0;                                //переменная опции меню
  19.     scanf("%d", &switcher);
  20.     getchar();
  21.     switch (switcher)                                   //выбор опции из меню
  22.     {
  23.     case 1:{
  24.                FILE* data;                                         //указатель на файл
  25.                if (argc == 1){                                      //открыть файл как аргумент или data.txt
  26.                    data = fopen("data.txt", "r");                   //присваиваем значение указателю
  27.                }
  28.                else {
  29.                    data = fopen(argv[1], "r");
  30.                }
  31.  
  32.                if (data == NULL){                                   //если файл не существует - ошибка
  33.                    printf("Error! Cant locate the file");
  34.                    exit(1);
  35.                }
  36.  
  37.                //Буфер для вводу з файлу
  38.                char count_buffer[3];
  39.                if (fgets(count_buffer, 101, data) == NULL){        //якщо не має числа кубиків - помилка
  40.                    printf("Missing cubes count!");
  41.                    exit(1);
  42.                }
  43.                int cubes_count;                                     //переменная колличества кубиков
  44.                if ((cubes_count = atoi(count_buffer)) <= 0){         //проверка является ли колличество кубиков натуральным числом
  45.                    printf("Cubes count is not natural number!");
  46.                    exit(1);
  47.                }
  48.  
  49.                char name[101];                                     //переменная имени
  50.                if (fgets(name, 101, data) == NULL){                 //проверка на считывание имени
  51.                    printf("Wrong input name");
  52.                    exit(1);
  53.                }
  54.  
  55.                char **cubes_data_array;                             //массив считанных с кубиков данных
  56.                cubes_data_array = new char*[cubes_count];           //выделение памяти
  57.                for (int i = 0; i < cubes_count; i++)
  58.                {
  59.                    cubes_data_array[i] = new char[6];
  60.                }
  61.                for (int i_cube = 0; i_cube < cubes_count; i_cube++){
  62.                    for (int i_side = 0; i_side < 6; i_side++){
  63.                        char ch = fgetc(data);
  64.                        if ((ch == '\n') || (ch == EOF)){            //если конец файла или нет данных - ошибка
  65.                            printf("Wrong cubes info");
  66.                            exit(1);
  67.                        }
  68.                        cubes_data_array[i_cube][i_side] = ch;      //сохраняет информацию на кубик и его сторону
  69.                    }
  70.                    fgetc(data);
  71.                }
  72.  
  73.                fclose(data);                                       //закрываем файл
  74.  
  75.  
  76.                int name_length;                                    //переменная длинны имени
  77.                for (int i = 0; i < 101; i++){                       //узнаем длинну имени
  78.                    if (name[i] == '\n'){
  79.                        name_length = i;
  80.                        break;
  81.                    }
  82.                }
  83.  
  84.                int *order = new int[name_length];                  //переменная порядка букв
  85.                for (int i = 0; i < name_length; i++){
  86.                    order[i] = -1;                                  //заполнение массива
  87.                }
  88.  
  89.                bool *cube_available = new bool[cubes_count];       //переменная наличия кубика
  90.                for (int i = 0; i < cubes_count; i++){
  91.                    cube_available[i] = true;                       //заполнение массива
  92.                }
  93.  
  94.                int letter_place = 0;                               //переменная места буквы
  95.  
  96.                while (letter_place < name_length && letter_place >= 0)//пока место буквы меньше длинны слова и больше или равняеться 0
  97.                {
  98.  
  99.                    char target_letter = name[letter_place];
  100.                    bool found_target = false;
  101.                    for (int i_cube = 0; i_cube < cubes_count; i_cube++){        //найти нужный кубик
  102.                        if (cube_available[i_cube]){                                  //проверить есть ли нужная буква на кубике
  103.                            for (int i_side = 0; i_side < 6; i_side++){
  104.                                if (cubes_data_array[i_cube][i_side] == target_letter){      //если нужная буква
  105.                                    order[letter_place] = i_cube;                           //записываем в массив порядка букв
  106.                                    cube_available[i_cube] = false;                         //записываем, что кубик использован
  107.                                    found_target = true;                                    //записываем, что цель найдена
  108.                                    break;
  109.                                }
  110.                            }
  111.                            if (found_target){
  112.                                break;
  113.                            }
  114.                        }
  115.                    }
  116.                    if (found_target){
  117.                        letter_place++;                                         //переходим к следующей букве
  118.                    }
  119.                    else {
  120.                        cube_available[order[letter_place]] = true;             //оставляем кубик
  121.                        order[letter_place] = -1;                               //заполняем значениями, которые показывают отсутствие
  122.                        letter_place--;
  123.                    }
  124.                }
  125.                if (letter_place == -1){                                        //если порядок не найден - ошибка
  126.                    printf("There is no variants\n");
  127.                }
  128.                else {                                                        //иначе - порядок найден
  129.                    printf("There is variant:\n");
  130.                    for (int i = 0; i < name_length; i++){
  131.                        printf("%d", order[i] + 1);
  132.                        printf("%s", "\n");
  133.                    }
  134.                }
  135.                printf("%s", "Press any key to exit");
  136.                _getch();
  137.             }
  138.             goto start;
  139.     case 2:{
  140.                printf("Goodbye!");
  141.                _getch();
  142.                exit(0);}
  143.  
  144.     }
  145.     return 0;
  146. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement