Print all sequences starting with n and consecutive difference limited to k in C++

C++Server Side ProgrammingProgramming

In this problem, we are given three variables n, s, and k and we have to print all the possible sequences that start with the number n and length s having the absolute difference between consecutive elements less than k.

Let’s take an example to understand the topic better −

Input: n = 3, s = 3 , k = 2
Output:
3 3 3
3 3 4
3 3 2
3 4 4
3 4 5
3 4 3
3 2 2
3 2 3
3 2 1

In this problem, we need to obtain the absolute difference less k. For this, we can get a sequence that has elements that are greater to obtain positive difference and lesser to obtain a negative difference.

For this, we will start with n and the make a recursive call to the elements at each consecutive position. A loop from 0 to k-1 and add it to the number to the number. Similarly going for the negative side also.

Example

#include <bits/stdc++.h>
using namespace std;
void printConsicutiveNumbers(vector& v, int n, int s, int k){
if (s == 0) {
for (int i = 0; i < v.size(); i++)
cout<<v[i]<<" ";
cout << endl;
return;
}
for (int i = 0; i < k; i++) {
v.push_back(n + i);
printConsicutiveNumbers(v, n + i, s - 1, k);
v.pop_back();
}
for (int i = 1; i < k; i++) {
v.push_back(n - i);
printConsicutiveNumbers(v, n - i, s - 1, k);
v.pop_back();
}
}
int main(){
int n = 3, s = 3, k = 2;
cout<<"The sequence is :\n";
vector<int> v;
v.push_back(n);
printConsicutiveNumbers(v, n, s - 1, k);
return 0;
}

Output

The sequence is −

3 3 3
3 3 4
3 3 2
3 4 4
3 4 5
3 4 3
3 2 2
3 2 3
3 2 1
Updated on 17-Jan-2020 11:01:29