Advertisement
Alyks

Untitled

Apr 9th, 2020
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.83 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <fstream>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. struct LinearList {
  9. public:
  10.     double value;
  11.     LinearList *next;
  12.  
  13.     bool inputElement() {
  14.         bool notCorrect = true;
  15.         bool isSuccess = true;
  16.         while(notCorrect && isSuccess) {
  17.             string input;
  18.             getline(cin, input);
  19.             if(input == "стоп") {
  20.                 isSuccess = false;
  21.                 next = nullptr;
  22.             } else {
  23.                 try {
  24.                     value = stod(input);
  25.                     notCorrect = false;
  26.                 } catch (...) {
  27.                     cout << "Вводимый элемент должен быть вещественным числом, повторите ввод" << endl;
  28.                 }
  29.             }
  30.         }
  31.         return isSuccess;
  32.     }
  33.  
  34.     void inputExactElement(double el) {
  35.         value = el;
  36.     }
  37.  
  38.     vector<double> toVector() {
  39.         vector<double> arr;
  40.         LinearList *currList = this;
  41.         while(currList != nullptr) {
  42.             arr.push_back(currList->value);
  43.             currList = currList->next;
  44.         }
  45.         return arr;
  46.     }
  47.  
  48.     void sort() {
  49.         vector<double> arr = this->toVector();
  50.         for(int i = 0; i < arr.size(); i++) {
  51.             int minIdx = i;
  52.             for(int j = i; j < arr.size(); j++) {
  53.                 double el = arr[j];
  54.                 double min = arr[minIdx];
  55.                 if(el < min)
  56.                     minIdx = j;
  57.             }
  58.             if(arr[minIdx] != arr[i]) {
  59.                 double tmp = arr[minIdx];
  60.                 arr[minIdx] = arr[i];
  61.                 arr[i] = tmp;
  62.             }
  63.         }
  64.         LinearList *currList = this;
  65.         int i = 0;
  66.         while(currList != nullptr) {
  67.             currList->value = arr[i];
  68.             currList = currList->next;
  69.             i++;
  70.         }
  71.     }
  72. };
  73.  
  74. LinearList* createLinearList(int i) {
  75.     LinearList *list = new LinearList();
  76.     cout << "Чтобы прекратить ввод элементов списка, введите [стоп]" << endl;
  77.     cout << "Введите " << i << "-й элемент списка" << endl;
  78.     if(list->inputElement()) {
  79.         list->next = createLinearList(i+1);
  80.     } else {
  81.         if(i > 2)
  82.             list = nullptr;
  83.         else {
  84.             cout << "Добавьте хотя бы 2 элемента в список" << endl;
  85.             return createLinearList(i);
  86.         }
  87.     }
  88.     return list;
  89. }
  90.  
  91. LinearList* createLinearListFromArray(vector<double> &arr) {
  92.     LinearList *list = new LinearList();
  93.     LinearList *currList = list;
  94.     for(int i = 0; i < arr.size(); i++) {
  95.         double el = arr[i];
  96.         currList->inputExactElement(el);
  97.         if(i == arr.size()-1)
  98.             currList->next = nullptr;
  99.         else
  100.             currList->next = new LinearList();
  101.         currList = currList->next;
  102.     }
  103.     return list;
  104. }
  105.  
  106. string vectorToStr(vector<double> &arr) {
  107.     string str;
  108.     for(double el : arr)
  109.         str += to_string(el) + " ";
  110.     return str;
  111. }
  112.  
  113. void showResult(vector<double> &arr) {
  114.     if(arr.size() > 0) {
  115.         cout << "Количество элементов, которые содержатся в обоих списках в указанном порядке = " << arr.size() << endl;
  116.         cout << "Совпадающие элементы:" << endl;
  117.         cout << vectorToStr(arr) << endl;
  118.     } else {
  119.         cout << "Повторяющихся по порядку элементов в данных списках нет" << endl;
  120.     }
  121. }
  122.  
  123. void showList(LinearList *list) {
  124.     LinearList *currList = list;
  125.     while(currList != nullptr) {
  126.         cout << currList->value << " ";
  127.         currList = currList->next;
  128.     }
  129.     cout << endl;
  130. }
  131.  
  132. vector<double> findMatchingEls(LinearList &list1, LinearList &list2) {
  133.     vector<double> arr1 = list1.toVector();
  134.     vector<double> arr2 = list2.toVector();
  135.     vector<double> matchingEls;
  136.     int size = arr1.size();
  137.     if(arr2.size() < arr1.size())
  138.         size = arr2.size();
  139.     for(int i = 0; i < size; i++) {
  140.         double el1 = arr1[i];
  141.         double el2 = arr2[i];
  142.         if(el1 == el2)
  143.             matchingEls.push_back(el1);
  144.     }
  145.     return matchingEls;
  146. }
  147.  
  148. void sortLists(LinearList &list1, LinearList &list2) {
  149.     cout << "Отсортированный по неубыванию 1-й список:" << endl;
  150.     list1.sort();
  151.     showList(&list1);
  152.     cout << "Отсортированный по неубыванию 2-й список:" << endl;
  153.     list2.sort();
  154.     showList(&list2);
  155. }
  156.  
  157. void saveResult(vector<double> &arr) {
  158.     cout << "Хотите сохранить результат в файл?" << endl;
  159.     string choice;
  160.     bool notCorrect = true;
  161.     while(notCorrect) {
  162.         cout << "Введите либо [д], либо [н]" << endl;
  163.         getline(cin, choice);
  164.         if(choice == "д" || choice == "н")
  165.             notCorrect = false;
  166.     }
  167.     if(choice == "д") {
  168.         cout << "Введите имя файла" << endl;
  169.         string fileName;
  170.         getline(cin, fileName);
  171.         ofstream file;
  172.         file.open(fileName+".txt");
  173.         if(file.is_open()) {
  174.             if(arr.size() > 0) {
  175.                 file << "Количество элементов, которые содержатся в обоих списках в указанном порядке = " << arr.size() << endl;
  176.                 file << "Совпадающие элементы:" << endl;
  177.                 file << vectorToStr(arr) << endl;
  178.             } else {
  179.                 file << "Повторяющихся по порядку элементов в данных списках нет" << endl;
  180.             }
  181.             file.close();
  182.         } else {
  183.             cout << "Произошла ошибка при попытке сохранить файл" << endl;
  184.         }
  185.     }
  186. }
  187.  
  188. void trim(std::string &src) {
  189.     src.erase(std::find_if_not(src.rbegin(), src.rend(), ::isspace).base(), src.end());
  190.     src.erase(src.begin(), std::find_if_not(src.begin(), src.end(), ::isspace));
  191. }
  192.  
  193. vector<string> split(string str, string delimiter) {
  194.     vector<string> result;
  195.     int pos = 0;
  196.     while (pos != -1) {
  197.         pos = str.find(delimiter);
  198.         result.push_back(str.substr(0, pos));
  199.         str.erase(0, pos + delimiter.length());
  200.     }
  201.     return result;
  202. }
  203.  
  204. bool isFileCorrect(ifstream &file, int lines) {
  205.     file.seekg(0);
  206.     for(int i = 0; i < lines; i++) {
  207.         string line;
  208.         getline(file, line);
  209.         vector<string> list = split(line, " ");
  210.         if(list.size() < 2)
  211.             return false;
  212.         try {
  213.             for (string el : list)
  214.                 stod(el);
  215.         } catch (...) {
  216.             return false;
  217.         }
  218.     }
  219.     return true;
  220. }
  221.  
  222. vector<LinearList> inputListsFromFile() {
  223.     const int LINES = 2;
  224.     vector<LinearList> lists(LINES);
  225.     bool notCorrect = true;
  226.     while(notCorrect) {
  227.         cout << "Введите путь к файлу" << endl;
  228.         string filePath;
  229.         getline(cin, filePath);
  230.         ifstream file(filePath);
  231.         if(file.good()) {
  232.             if(isFileCorrect(file, LINES)) {
  233.                 file.seekg(0);
  234.                 for(int i = 0; i < LINES; i++) {
  235.                     string line;
  236.                     getline(file, line);
  237.                     trim(line);
  238.                     vector<string> list = split(line, " ");
  239.                     vector<double> arr;
  240.                     for(string el : list)
  241.                         arr.push_back(stod(el));
  242.                     lists[i] = *createLinearListFromArray(arr);
  243.                 }
  244.                 notCorrect = false;
  245.             } else {
  246.                 cout << "Убедитесь, что в файле содержатся 2 списка чисел (каждый на своей строке), состоящих только из вещественных чисел, разделенных одиночным пробелом и повторите ввод" << endl;
  247.             }
  248.             file.close();
  249.         } else {
  250.             cout << "Произошла ошибка при попытке открыть файл. Убедитесь, что файл существует и повторите ввод" << endl;
  251.             notCorrect = true;
  252.         }
  253.     }
  254.     return lists;
  255. }
  256.  
  257. vector<LinearList> inputListsFromConsole() {
  258.     cout << "Введите элементы первого списка" << endl;
  259.     LinearList list1 = *createLinearList(1);
  260.     cout << "Введите элементы второго списка" << endl;
  261.     LinearList list2 = *createLinearList(1);
  262.     return vector<LinearList>{list1, list2};
  263. }
  264.  
  265. vector<LinearList> inputLists() {
  266.     cout << "Введите [f], если хотите ввести данные из файла или [c], если хотите ввести данные из консоли" << endl;
  267.     string choice;
  268.     bool notCorrect = true;
  269.     while(notCorrect) {
  270.         getline(cin, choice);
  271.         if(choice == "f" || choice == "c")
  272.             notCorrect = false;
  273.         else
  274.             cout << "Вы должны ввести либо [f], либо [c]" << endl;
  275.     }
  276.  
  277.     if(choice == "c")
  278.         return inputListsFromConsole();
  279.     return inputListsFromFile();
  280. }
  281.  
  282. int main() {
  283.     cout << "Данная программа проверяет содержатся ли элементы первого линейного односвязного списка во втором по порядку" << endl;
  284.     vector<LinearList> lists = inputLists();
  285.     sortLists(lists[0], lists[1]);
  286.     vector<double> matching = findMatchingEls(lists[0], lists[1]);
  287.     showResult(matching);
  288.     saveResult(matching);
  289.     return 0;
  290. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement