Skip to content

Instantly share code, notes, and snippets.

@alguerocode
Created June 6, 2022 11:10
Show Gist options
  • Save alguerocode/c579bed1085093a10ecd9bcddf9f3504 to your computer and use it in GitHub Desktop.
Save alguerocode/c579bed1085093a10ecd9bcddf9f3504 to your computer and use it in GitHub Desktop.
c++ function to extract all the Subsequences in the array of numbers ranged between 1 to 4
#include <iostream>
int subsequence(int arr[], int length)
{
// counter the number of Subsequences
int counter = 0;
for (size_t i = 0; i < length; i++)
{
for (size_t j = i; j < length; j++)
{
if (i == j)
{ // print the first range ( it's most likly only on item)
std::cout << '[' << arr[i] << ']' << std::endl;
counter++;
continue;
}
if(j - i >= 2) {
std::cout << '[' << arr[i] << ", " << arr[j] << ']' << std::endl;
counter++;
}
// print all the number between range i and j
std::cout << '[';
for (size_t k = i; k < j; k++)
{
std::cout << arr[k] << ", ";
}
std::cout << arr[j];
std::cout << ']' << std::endl;
counter++;
if (j - i == 3)
{
for (size_t k = i + 1; k < j; k++)
{
if (j - k > 2)
{
std::cout << '[' << arr[i] << ", ";
std::cout << arr[k] << ", ";
std::cout << arr[j] << ']';
counter++;
}
std::cout << '[' << arr[i] << ", ";
for (size_t l = k; l < j; l++)
{
std::cout << arr[k] << ", ";
}
std::cout << arr[j];
std::cout << ']';
counter++;
}
}
}
std::cout << std::endl;
}
return counter;
}
int main()
{
int arr[] = {1, 2, 3,4, 5};
int length = sizeof(arr) / sizeof(*arr);
int val = subsequence(arr, length);
std::cout << std::endl;
std::cout << val;
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment