Print all distinct integers that can be formed by K numbers from a given array of N numbers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of N integers and a number K. Our task is to print all distinct numbers that can be created by adding any K elements from the array. While choosing any number can be repeated K times.

Let’s take an example to understand the problem −

Input: array = {2, 5, 13, 9} K = 2
Output: 2,7,15,11,10,18,14,26,22
Explaination: 2 elements added :
2+2=4, 2+5=7, 2+13=15, 2+9=11, 5+5=10, 5+13=18, 5+9=14, 13+13=26, 13+9=22, 9+9=18

To solve this problem, we will find all combinations of the k element from the array. For this, we will use recursion which will be called recursively to generate numbers. To avoid duplicate values, we will store the numbers in a set.

Example

The code will show the implementation of our solution −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
set<int> distNumbers;
void generateNumberFromArray(int count, int arr[], int n, int num, int k) {
   if (k == count) {
      distNumbers.insert(num);
      return;
   }
   for (int i = 0; i < n; i++) {
      generateNumberFromArray(count + 1, arr, n, num + arr[i], k);
   }
}
void printDistinctIntegers(int k, int arr[], int n) {
   generateNumberFromArray(0, arr, n, 0, k);
   cout<<"The "<<distNumbers.size()<<" distinct integers are:\n";
   while (!distNumbers.empty()) {
      cout << *distNumbers.begin() <<"\t";
      distNumbers.erase(*distNumbers.begin());
   }
}
int main() {
   int arr[]={ 2, 5, 13, 9 };
   int n=4;
   int k=2;
   printDistinctIntegers(k, arr, n);
   return 0;
}

Output

The 9 distinct integers are −
4 7 10 11 14 15 18 22 26
raja
Published on 22-Jan-2020 12:17:11
Advertisements