redmanexe

Lab3Challenge3CPP

Nov 3rd, 2024
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 8.46 KB | None | 0 0
  1. #include <fstream>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. constexpr string DEFAULT_INPUT_FILE = "./input.txt";
  7. constexpr string DEFAULT_OUTPUT_FILE = "./output.txt";
  8.  
  9. constexpr int PRINT_TYPE_MIN = 0;
  10. constexpr int PRINT_TYPE_MAX = 2;
  11.  
  12. constexpr int SCAN_TYPE_MIN = 0;
  13. constexpr int SCAN_TYPE_MAX = 1;
  14.  
  15. constexpr int ARRAY_LENGTH_MIN = 1;
  16. constexpr int ARRAY_LENGTH_MAX = 1000;
  17.  
  18. constexpr int ARRAY_VALUES_MIN = -10000;
  19. constexpr int ARRAY_VALUES_MAX = 10000;
  20.  
  21. constexpr int ERR_READ_INT_VALUE = 0x10000000;
  22.  
  23. void sortArray(int* arr, const int length) {
  24.     cout << "[";
  25.     for (int k = 0; k < length - 1; k++) {
  26.         cout << arr[k] << ", ";
  27.     }
  28.     cout << arr[length - 1] << "]; i = " << 0 << "\n";
  29.    
  30.     for (int i = 1; i < length; i++) {
  31.         int key = arr[i];
  32.  
  33.         int j = i - 1;
  34.         while (j >= 0 && arr[j] > key) {
  35.             arr[j + 1] = arr[j];
  36.             j = j - 1;
  37.         }
  38.         arr[j + 1] = key;
  39.  
  40.         cout << "[";
  41.         for (int k = 0; k < length - 1; k++) {
  42.             cout << arr[k] << ", ";
  43.         }
  44.         cout << arr[length - 1] << "]; i = " << i << "\n";
  45.     }
  46. }
  47. bool isTextFile(const string &filePath)
  48. {
  49.     bool isTxt;
  50.     isTxt = (filePath.length() > 4 &&
  51.              filePath[filePath.length() - 4] == '.' &&
  52.              filePath[filePath.length() - 3] == 't' &&
  53.              filePath[filePath.length() - 2] == 'x' &&
  54.              filePath[filePath.length() - 1] == 't');
  55.  
  56.     return isTxt;
  57. }
  58. bool checkFileAvailability(const string &filePath, const bool read)
  59. {
  60.     ios::openmode mode;
  61.     if (read)
  62.         mode = ifstream::in;
  63.     else
  64.         mode = ifstream::app;
  65.     fstream file(filePath, mode);
  66.     bool available;
  67.     available = file.good();
  68.     file.close();
  69.     if (available && !isTextFile(filePath))
  70.         available = false;
  71.  
  72.     return available;
  73. }
  74. int takeIntValueFromConsole(const string& text)
  75. {
  76.     bool isInCorrect;
  77.     int value;
  78.     isInCorrect = true;
  79.     while (isInCorrect)
  80.     {
  81.         cout << text;
  82.         cin >> value;
  83.         isInCorrect = false;
  84.         if (cin.fail())
  85.         {
  86.             cout << "Введите число, а не строку или что-то иное!\n";
  87.             cin.clear();
  88.             cin.ignore(numeric_limits<streamsize>::max(), '\n');
  89.             isInCorrect = true;
  90.         }
  91.     }
  92.  
  93.     return value;
  94. }
  95. int takeIntValueInRangeFromConsole(const string& text, const int min, const int max)
  96. {
  97.     bool isInCorrect;
  98.     int value;
  99.     isInCorrect = true;
  100.     value = 0;
  101.     while (isInCorrect)
  102.     {
  103.         value = takeIntValueFromConsole(text);
  104.         isInCorrect = false;
  105.         if (value < min || value > max)
  106.         {
  107.             cout << "Число должно находится в границах от " << min << " до " << max << "\n";
  108.             cin.clear();
  109.             cin.ignore(numeric_limits<streamsize>::max(), '\n');
  110.             isInCorrect = true;
  111.         }
  112.     }
  113.  
  114.     return value;
  115. }
  116. string takeCorrectFile(const bool input)
  117. {
  118.     bool isInCorrect;
  119.     string value;
  120.     isInCorrect = true;
  121.     cin.ignore(numeric_limits<streamsize>::max(), '\n');
  122.     while(isInCorrect) {
  123.         if (input)
  124.             cout << "Введите путь до входного файла (пустая строка – " << DEFAULT_INPUT_FILE << "): ";
  125.         else
  126.             cout << "Введите путь до выходного файла (пустая строка – " << DEFAULT_OUTPUT_FILE << "): ";
  127.         getline(cin, value);
  128.         if (value.empty())
  129.         {
  130.             if (input)
  131.                 value = DEFAULT_INPUT_FILE;
  132.             else
  133.                 value = DEFAULT_OUTPUT_FILE;
  134.         }
  135.         isInCorrect = false;
  136.         if (!checkFileAvailability(value, input)) {
  137.             isInCorrect = true;
  138.             cout << "Путь ведёт до файла, который недоступен или который не является текстовым файлом!\n";
  139.         }
  140.     }
  141.  
  142.     return value;
  143. }
  144. int takeIntValueFromFile(ifstream &reader)
  145. {
  146.     int value;
  147.     reader >> value;
  148.     if (reader.fail() || reader.get() == ',')
  149.         value = ERR_READ_INT_VALUE;
  150.     reader.clear();
  151.  
  152.     return value;
  153. }
  154. int* readArrayFromFile(int* n)
  155. {
  156.     bool isInCorrect = true;
  157.     int* sequences;
  158.     while (isInCorrect)
  159.     {
  160.         string filePath = takeCorrectFile(true);
  161.         isInCorrect = false;
  162.         ifstream file(filePath);
  163.         *n = takeIntValueFromFile(file);
  164.         if (*n > (ARRAY_LENGTH_MIN - 1) && *n < (ARRAY_LENGTH_MAX + 1))
  165.         {
  166.             sequences = new int[*n];
  167.             for (int i = 0; i < *n; i++)
  168.             {
  169.                 sequences[i] = takeIntValueFromFile(file);
  170.                 if (sequences[i] == ERR_READ_INT_VALUE)
  171.                     isInCorrect = true;
  172.             }
  173.         }
  174.         else
  175.             isInCorrect = true;
  176.  
  177.         if (*n == ERR_READ_INT_VALUE && isInCorrect)
  178.         {
  179.             cout << "В файле содержится неверные значения! Введите путь до файла с верным содержимым!\n";
  180.         }
  181.         else if (isInCorrect)
  182.         {
  183.             cout << "Массив не может быть размером меньше, чем " + to_string(ARRAY_LENGTH_MIN) + "!\n";
  184.         }
  185.     }
  186.  
  187.     return sequences;
  188. }
  189. int* readArrayFromConsole(int* n)
  190. {
  191.     *n = takeIntValueInRangeFromConsole("Введите длину массива (значение должно быть в границах от " + to_string(ARRAY_LENGTH_MIN) + " и до " + to_string(ARRAY_LENGTH_MAX) + "): ", ARRAY_LENGTH_MIN, ARRAY_LENGTH_MAX);
  192.     int* sequences;
  193.  
  194.     sequences = new int[*n];
  195.     for (int i = 0; i < *n; i++)
  196.         sequences[i] = takeIntValueInRangeFromConsole("Элемент " + to_string(i + 1) + " последовательности A (значение должно быть в границах от " + to_string(ARRAY_VALUES_MIN) + " и до " + to_string(ARRAY_VALUES_MAX) + "): ", ARRAY_VALUES_MIN, ARRAY_VALUES_MAX);
  197.  
  198.     return sequences;
  199. }
  200. int* readArray(int* n)
  201. {
  202.     int type;
  203.     int* sequences;
  204.     cout << "\nКак считать значения для поиска решения?\n";
  205.     cout << "0 - Из ввода с клавиатуры (консоль)\n";
  206.     cout << "1 - Из файла\n";
  207.     type = takeIntValueInRangeFromConsole("Выбранный вариант ввода: ", SCAN_TYPE_MIN, SCAN_TYPE_MAX);
  208.     if (type == 1)
  209.         sequences = readArrayFromFile(n);
  210.     else
  211.         sequences = readArrayFromConsole(n);
  212.  
  213.     return sequences;
  214. }
  215. bool saveResultIntoFile(const string &filePath, const int* arr, const int length)
  216. {
  217.     bool saved;
  218.     saved = true;
  219.     ofstream file(filePath);
  220.     if (file.good())
  221.     {
  222.         for (int i = 0; i < length; i++)
  223.             file << arr[i] << " ";
  224.     }
  225.     else
  226.         saved = false;
  227.     file.close();
  228.  
  229.     return saved;
  230. }
  231. void printResultIntoConsole(const int* arr, const int length)
  232. {
  233.     cout << "\nОтсортированный массив:\n";
  234.     for (int i = 0; i < length; i++)
  235.         cout << arr[i] << " ";
  236.     cout << "\n";
  237. }
  238. void printResult(const int* arr, const int length)
  239. {
  240.     bool saved;
  241.     int type;
  242.     cout << "\nКуда вывести результат решения?\n";
  243.     cout << "0 - Только консоль\n";
  244.     cout << "1 - Только в файл\n";
  245.     cout << "2 - И в файл, и в консоль\n";
  246.     type = takeIntValueInRangeFromConsole("Выбранный вариант вывода: ", PRINT_TYPE_MIN, PRINT_TYPE_MAX);
  247.     saved = false;
  248.     string output;
  249.     switch (type)
  250.     {
  251.         case 0:
  252.             printResultIntoConsole(arr, length);
  253.         break;
  254.         case 1:
  255.             output = takeCorrectFile(false);
  256.             saved = saveResultIntoFile(output, arr, length);
  257.         break;
  258.         case 2:
  259.             output = takeCorrectFile(false);
  260.             saved = saveResultIntoFile(output, arr, length);
  261.             printResultIntoConsole(arr, length);
  262.         break;
  263.     }
  264.  
  265.     if (saved)
  266.         cout << "Результат записан в выходной файл!" << "\n";
  267. }
  268. int main()
  269. {
  270.     cout << "3. Сортировка методом простых вставок.\n";
  271.     int* array;
  272.     int n;
  273.     array = readArray(&n);
  274.     sortArray(array, n);
  275.     printResult(array, n);
  276.  
  277.     delete[] array;
  278.  
  279.     return 0;
  280. }
Advertisement
Add Comment
Please, Sign In to add comment