Print all increasing sequences of length k from first n natural numbers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two integers K and n. Our task is to print all increasing sequences of length K using first n natural numbers.

The increasing sequence is a sequence of numbers in which the value of the next element is greater than the previous one.

Let’s take an example to understand the problem −

Input: n = 4, K = 2
Output:
1 2
1 3
1 4
2 3
2 4
3 4

To solve this problem, we will create a k length array that stores the current sequence of the array. And for every position in the array, we will check the previous element and select the next elements that are greater than the previous one. We will one by one try to fix all values from 1 to n.

Example

Program to illustrate the above logic −

 Live Demo

#include<iostream>
using namespace std;
void printSequence(int arr[], int k) {
   for (int i=0; i<k; i++)
      cout<<arr[i]<<" ";
   cout<<endl;
}
void printKLengthSequence(int n, int k, int &len, int arr[]) {
   if (len == k) {
      printSequence(arr, k);
      return;
   }
   int i = (len == 0)? 1 : arr[len-1] + 1;
   len++;
   while (i<=n) {
      arr[len-1] = i;
      printKLengthSequence(n, k, len, arr);
      i++;
   }
   len--;
}
void generateSequence(int n, int k) {
   int arr[k];
   int len = 0;
   printKLengthSequence(n, k, len, arr);
}
int main() {
   int k = 3, n = 4;
   cout<<"Sequence of length "<<k<<" generated using first "<<n<<" natural numbers :\n";
   generateSequence(n, k);
   return 0;
}

Output

A sequence of length 3 generated using first 4 natural numbers −
1 2 3
1 2 4
1 3 4
2 3 4
raja
Published on 22-Jan-2020 16:00:00
Advertisements