

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print all sequences starting with n and consecutive difference limited to k in C++
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
- Related Questions & Answers
- Print all increasing sequences of length k from first n natural numbers in C++
- Print all possible sums of consecutive numbers with sum N in C++
- Print all sequences of given length in C++
- Python - Consecutive Ranges of K greater than N
- Print all longest common sub-sequences in lexicographical order in C++
- Count all distinct pairs with difference equal to k in C++
- Find all distinct pairs with difference equal to k in Python
- Print all n-digit numbers with absolute difference between sum of even and odd digits is 1 in C++
- Count all sub-sequences having product <= K – Recursive approach in C++
- Print all Proth primes up to N in C++
- Print all safe primes below N in C++
- Print all multiplicative primes <= N in C++
- Longest consecutive path from a given starting character
- Program to find number of sequences after adjacent k swaps and at most k swaps in Python
- C++ program to find n valid bracket sequences
Advertisements