1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#include <iostream>
#include <vector>
#include <cstdlib>
#include <fstream>
const char* ERROR_NOT_INT = "Error: must be integer!";
const char* ERROR_WRONG_ARRAY_SIZE = "Error: size of the array must be greater than 0!";
const char* ERROR_FILE = "Error: file can't be opened!";
int findLongestDecrSeq(const int array[], const int arr_size)
{
int lds[arr_size];
int i, j, max = 0;
for (i = 0; i < arr_size; i++)
{ std::cout << array[i] <<" ";
lds[i] = 1;}
for (i = 1; i < arr_size; i++)
for (j = 0; j < i; j++)
if (array[i] < array[j] && lds[i] < lds[j] + 1)
lds[i] = lds[j] + 1;
for (i = 0; i < arr_size; i++)
if (max < lds[i])
max = lds[i];
return max;
}
int main()
{
int array, arr_size, i, fileName, option;
try
{
int choice;
std::cout << "Choose type of array for finding maximum length of subsequence\n";
std::cout << "1. Array with constant values\n"
<< "2. Array with random values\n"
<< "3. Array with values from file\n";
std::cin >> choice;
switch(choice)
{
case 1:
{
int array[] = {6, 5, 4, 8, 1};
int arr_size = sizeof(array) / sizeof(array[0]);
std::cout << "\n Length of longest decreasing sequence is " << findLongestDecrSeq(array, arr_size);
break;
}
case 2:
{
std::cout << "Input size of array";
std::cin >> arr_size;
std::vector<int> array(arr_size);
if (!std::cin)
{
throw ERROR_NOT_INT;
}
if (arr_size < 1)
{
throw ERROR_WRONG_ARRAY_SIZE;
}
for (int i = 0; i < arr_size; i++)
{
array[i] = rand() % 100 + 1;
}
std::cout << "\n Length of longest decreasing sequence is " << findLongestDecrSeq( array[], arr_size); //compiler writes "73 104 [Error] expected primary-expression before ']' token" here
break;
}
case 3:
{
int var;
std::cout << "Enter a name of input file: " << std::endl;
std::cin >> fileName;
std::ifstream file("input.txt");
if (!file.is_open()) {
throw ERROR_FILE;
}
file >> arr_size;
std::vector<int> array(arr_size);
while(!file.eof())
{
for(i = 0; i < arr_size; i++)
{
file >> var;
array[i] = var;
}
file.close();
std::cout << "\n Length of longest decreasing sequence is " << findLongestDecrSeq(array[], arr_size); //the same is here
}
}
}
}
catch (const char *error) {
std::cerr << std::endl << error << std::endl;
return -1;
}
return 0;
}
| |