Repetitive Permutations with summation bounds - c++

I try to generate all permutations with repetition of a number array by putting bound on summation of values.
Example;
I have my array {3,4,5,6} and my bound is 11.
I would like to generate all repetitive permutations reaching and just crossing 11 as:
3 3 3 3 //
3 4 3 3 //
3 3 5 3 //
3 3 3 6 //
3 4 4 3 //
4 4 4 //
6 6 //
6 4 3 //
5 5 5 //
..
So the cardinalty doesnt need to be the same as what we have with array.
Thanks for help in advance
I tried the following conversion from Java code, I got it, but still C++ gave the error "Unhandled exception":
void permute(int array[], int start[]){
int sum=0;
for (int i=0; i< sizeof(start)/sizeof(start[0]); i++) {
sum+= start[i];
}
if (sum >= 11) {
for (int n=0; n< sizeof(start) / sizeof(start[0]); n++)
cout << start[n] << " ";
cout << "\n";
return;
}
for (int i= 0; i < sizeof(array) / sizeof(array[0]) ; i++) {
int* newStart = new int[sizeof(start) / sizeof(start[0]) + 1];
memcpy (newStart, start, sizeof(start) / sizeof(start[0]) + 1);
newStart[sizeof(start) / sizeof(start[0])] = array[i];
permute(array, newStart);
}
}
void main ()
{
int array[] = {3,4,5,6};
int newarray[1];
for (int i=0; i< sizeof(array)/sizeof(array[0]); i++) {
newarray[0]=array[i];
permute(array, newarray);
}
system("pause");}
Additionally I would like to keep the indice numbers of all permutations and positions of each member. Example:
Permutation[1119] = [ 3 3 5 3],
Member[1119][1] = 3,
Member[1119][2] = 3 etc.

This is not so complicated. Because you're so vague about your language requirements, I took the freedom to invent my own pseudocode:
function generate(int[] array, int bound, int[] solution, int sum)
if (sum > bound)
print solution
else
for each elt in array
generate(array, bound, solution ++ [elt], sum + elt)
And call this as
generate([3, 4, 5, 6], 11, [], 0)

This is code for Java:
private static boolean checkConstraint(int[] array) {
int sum=0;
for (int i=0; i<array.length; i++) {
sum+= array[i];
}
//we found it, print
if (sum >= 11) {
System.out.println(Arrays.toString(array));
return true;
}
return false;
}
public static void permute(int[] array, int[] start){
if (checkConstraint(start)) {
return;
}
for (int i= 0; i < array.length; i++) {
int[] newStart= Arrays.copyOf(start, start.length + 1);
newStart[start.length] = array[i];
permute(array, newStart);
}
}
public static void main(String[] args) {
int[] array= {3,4,5,6};
for (int i=0; i<array.length; i++) {
permute(array, new int[] {array[i]});
}
}

Related

Arrays - Sum Of Two numbers as arrays of digits

Take as input N, the size of array. Take N more inputs - digits between 0 and 9 - and store that in an array. Take as input M, the size of second array and take M more input digits and store that in second array. Write a function that returns the sum of the numbers represented by the two arrays. Print the value returned.
Input:
4
1 0 2 9
5
3 4 5 6 7
Output:
3, 5, 5, 9, 6, END
Below is the code I have written for it, but it's not giving any result rather it crashes.
using namespace std;
int main()
{
int tsum,n,m,s,carry=0;
cin>>n;
int a[n],sum[]={0};
for(int i=0; i<n; i++)
{
cin>>a[i];
}
cin>>m;
int b[m];
for(int i=0; i<m; i++)
{
cin>>b[i];
}
s=max(n,m);
sum[s] = {0};
while(n>0 and m>0)
{
tsum=a[n]+b[m]+carry;
sum[s] = tsum%10;
carry = tsum/10;
n--;
m--;
s--;
}
if(n>m)
{
while(n>0)
{
tsum=a[n]+carry;
sum[s] = tsum%10;
carry = tsum/10;
n--;
s--;
}
}
if(m>n)
{
while(m>0)
{
tsum=b[m]+carry;
sum[s] = tsum%10;
carry = tsum/10;
m--;
s--;
}
}
for (int i=1; i<s; i++)
{
cout<<sum[i]<<", ";
}
cout<<"END";
return 0;
}```

Best way to remove non uniques values from an array, keep the order, and not use vectors?

I apologize if this has been asked, but I ran into a coding question, which was supposed to be simple but I struggled on. Please provide a link if already answered (I may just be bad at searching).
Question: Given the sample code fill in the function to return only unique values in the array. Values must keep order.
Example Input : 1, 2, 3, 10, 4, 3, 2, 10, 1, 11, 6
Example Output: 1 2 3 10 4 11 6
Below is my solution, but I can not seem to think of an easy solution that does not include the use of a vector to store unique values. The tester did not like the use of a vector so I can only assume additional headers / libraries were unacceptable. Any other solutions? I am guessing the tester was looking for the array to be filtered in place.
#include <iostream>
#include <vector> //I was not allowed to add this...
//Function to fill in...
int fxn(int *a, int size)
{
std::vector<int> temp;
for(int i(0); i < size; ++i)
{
bool found(false);
for(auto j : temp)
{
if( j == a[i])
{
found = true;
break;
}
}
if(!found)
{
temp.push_back(a[i]);
}
}
int *ptr_a = &a[0];
for(auto j : temp)
{
*ptr_a = j;
++ptr_a;
}
return size - temp.size();
}
//The rest untochable...
void print(int *a, int size)
{
for(int i(0); i < size; ++i)
{
std::cout << a[i] << " ";
}
std::cout << std::endl;
}
int main(void)
{
int a[] = { 1, 2, 3, 10, 4, 3, 2, 10, 1, 11, 6 };
int size = 11;
int count = fxn(a, size);
print(a, size - count);
return 0;
}
Admittedly, this problem would be easier if you could use external libraries, but if you are certain you cannot, it is still solvable.
I read the question incorrectly the first time. Here is a link to as similar question.
#include<iostream>
using namespace std;
int removeDuplicates(int arr[], int n)
{
int j = 0;
for (int i=0; i < n; i++){
for(int j=0;j<i;j++){
if(arr[i]==arr[j]){
n--;
for (int k=i; k<n; k++){
arr[k]=arr[k+1];
}
i--; // you forgot to decrement i
}
}
}
return n;
}

Deleting an even number in an array and shift the elements

I'm trying to write a code where there is a research of even numbers and then it deletes the even numbers and then shifts all the other elements.
i is for offset and are the actual position of the elements in the array.
k is the position of the even number in the array.
int k;
for(i=0; i < N; i++)
{
if(Array[i] % 2 == 0)
{
for(k=i+1; k < N; k++)
{
Array[k-1] = Array[k];
}
N--;
}
}
Array=[2,10,3,5,8,7,3,3,7,10] the even numbers should be removed, but a 10
stays in the Array=[10,3,5,7,3,3,7].
Now is more than 3 hours that I'm trying to figure out what's wrong in my code.
This appears to be some sort of homework or school assignment. So what's the actual problem with the posted code?
It is that when you remove an even number at index i, you put the number that used to be at index i + 1 down into index i. Then you continue the outer loop iteration, which will check index i + 1, which is the number that was at the original i + 2 position in the array. So the number that started out at Array[i + 1], and is now in Array[i], is never checked.
A simple way to fix this is to decrement i when you decrement N.
Though already answered, I fail to see the reason people are driving this through a double for-loop, repetitively moving data over and over, with each reduction.
I completely concur with all the advice about using containers. Further, the algorithms solution doesn't require a container (you can use it on a native array), but containers still make it easier and cleaner. That said...
I described this algorithm in general-comment above. you don't need nested loops fr this. You need a read pointer and a write pointer. that's it.
#include <iostream>
size_t remove_even(int *arr, size_t n)
{
int *rptr = arr, *wptr = arr;
while (n-- > 0)
{
if (*rptr % 2 != 0)
*wptr++ = *rptr;
++rptr;
}
return (wptr - arr);
}
int main()
{
int arr[] = { 2,10,3,5,8,7,3,3,7,10 };
size_t n = remove_even(arr, sizeof arr / sizeof *arr);
for (size_t i=0; i<n; ++i)
std::cout << arr[i] << ' ';
std::cout << '\n';
}
Output
3 5 7 3 3 7
If you think it doesn't make a difference, I invite you to fill an array with a million random integers, then try both solutions (the nested-for-loop approach vs. what you see above).
Using std::remove_if on a native array.
Provided only for clarity, the code above basically does what the standard algorithm std::remove_if does. All we need do is provide iterators (the array offsets and size will work nicely), and know how to interpret the results.
#include <iostream>
#include <algorithm>
int main()
{
int arr[] = { 2,10,3,5,8,7,3,3,7,10 };
auto it = std::remove_if(std::begin(arr), std::end(arr),
[](int x){ return x%2 == 0; });
for (size_t i=0; i<(it - arr); ++i)
std::cout << arr[i] << ' ';
std::cout << '\n';
}
Same results.
The idiomatic solution in C++ would be to use a STL algorithm.
This example use a C-style array.
int Array[100] = {2,10,3,5,8,7,3,3,7,10};
int N = 10;
// our remove_if predicate
auto removeEvenExceptFirst10 = [first10 = true](int const& num) mutable {
if (num == 10 && first10) {
first10 = false;
return false;
}
return num % 2 == 0;
};
auto newN = std::remove_if(
std::begin(Array), std::begin(Array) + N,
removeEvenExceptFirst10
);
N = std::distance(std::begin(Array), newN);
Live demo
You could use a std::vector and the standard function std::erase_if + the vectors erase function to do this:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> Array = {2, 10, 3, 5, 8, 7, 3, 3, 7, 10};
auto it = std::remove_if(
Array.begin(),
Array.end(),
[](int x) { return (x & 1) == 0 && x != 10; }
);
Array.erase(it, Array.end());
for(int x : Array) {
std::cout << x << "\n";
}
}
Output:
10
3
5
7
3
3
7
10
Edit: Doing it the hard way:
#include <iostream>
int main() {
int Array[] = {2, 10, 3, 5, 8, 7, 3, 3, 7, 10};
size_t N = sizeof(Array) / sizeof(int);
for(size_t i = 0; i < N;) {
if((Array[i] & 1) == 0 && Array[i] != 10) {
for(size_t k = i + 1; k < N; ++k) {
Array[k - 1] = Array[k];
}
--N;
} else
++i; // only step i if you didn't shift the other values down
}
for(size_t i = 0; i < N; ++i) {
std::cout << Array[i] << "\n";
}
}
Or simpler:
#include <iostream>
int main() {
int Array[] = {2, 10, 3, 5, 8, 7, 3, 3, 7, 10};
size_t N = sizeof(Array) / sizeof(int);
size_t k = 0;
for(size_t i = 0; i < N; ++i) {
if((Array[i] & 1) || Array[i] == 10) {
// step k after having saved this value
Array[k++] = Array[i];
}
}
N = k;
for(size_t i = 0; i < N; ++i) {
std::cout << Array[i] << "\n";
}
}

Recursive Permutation C++

I have problem with assignment, we need to implement recursive permutation in c++ for numbers.
Here is the code which is partly working, but missing some numbers.
I can't find where the problem is.
This code does work, but not exactly the right way.
This code take and array of number with size of that array.
in this case I am trying to solve the problem which appears when I send array longer than 3 numbers. If I send 3 numbers, output is:
///
1 2 3 /
1 3 2 /
3 1 2 /
2 1 3 /
2 3 1 /
3 2 1 /
Output in this case is correct. But when I set array to 4 and send size of it 4 I get:
///
1 2 3 4 /
1 2 4 3 /
1 4 2 3 /
4 1 2 3 /
**2 1 3 /
2 3 1 /
3 2 1 /**
3 2 1 4 /
3 2 4 1 /
3 4 2 1 /
4 3 2 1 /
Output is partly correct, but some numbers are missing.
Program should give output of all possible variations of numbers in array
#include <iostream>
using namespace std;
bool nextPermutation(int[],int);
void swap(int&, int&);
int Maxind(int[],int);
int Minind(int[],int);
void print (int[], int);
bool test (int[], int);
int fl=0;
int main() {
int a[]={1,2,3,4};
nextPermutation(a,4);
return 0;
}
void print(int a[], int s) {
for(int i=0; i<s; i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
bool nextPermutation(int a[], int s)
{
int i=Maxind(a,s);
if(fl==0)
print(a,s);
if(i!=0) {
swap(a[i],a[i-1]);
nextPermutation(a,s);
}
else if(i==0 && test(a,s))
{
int p=a[0];
for(int i=0; i<=s-2; i++)
a[i]=a[i+1];
fl=1;
nextPermutation(a,s-1);
a[s-1]=p;
fl=0;
nextPermutation(a,s);
}
else
return false;
}
bool test (int a[], int s) {
if (Maxind(a,s)==0 && Minind(a,s)==s-1)
return false;
else
return true;
}
void swap(int& a, int& b)
{
int t=a; a=b; b=t;
}
int Maxind(int a[], int s)
{
int m=a[0], ind=0;
for(int i=0; i<s; i++)
if(m<a[i]) {
m=a[i];
ind=i;
}
return ind;
}
int Minind(int a[], int s)
{
int m=a[0], ind=0;
for(int i=0; i<s; i++)
if(m>a[i]) {
m=a[i];
ind=i;
}
return ind;
}
You need to send all numbers of possibilities for permutation.
If you change your main function you will get the solution. Add a loop in main funciton and send to nextPermutation(a, i) with variable i
int main() {
for(int i = 1; i < 5; i++) {
int a[]= {1,2,3,4};
nextPermutation(a,i);
}
return 0;
}
You should debug your program and also i figure out that your s value is decrasing here:
else if(i==0 && test(a,s)) {
int p=a[0];
for(int i=0; i<=s-2; i++) {
a[i]=a[i+1];
}
fl=1;
nextPermutation(a,s-1);
//*** careful you are decreasing s here and your output gives 3 numbers. !!***
a[s]=p;
fl=0;
nextPermutation(a,s);
}
I just modified the nextPermutation method of your code as follows and it worked.
bool nextPermutation(int a[], int s)
{
if(s == 0)
return false;
int i=Maxind(a,s);
if(fl==0)
print(a,s);
if(i!=0) {
swap(a[i],a[i-1]);
if(fl == 0)
nextPermutation(a,s);
else{
int temp = fl;
fl = 0;
nextPermutation(a,s+temp);
}
}
else if(i==0){
int p=a[0];
for(int i=0; i<=s-2; i++)
a[i]=a[i+1];
a[s-1]=p;
fl+=1;
nextPermutation(a,s-1);
}
else
return false;
}
Also I removed the methods test and Minind as they are not useful in my code.

How can I iterate through every possible combination of n playing cards

How can I loop through all combinations of n playing cards in a standard deck of 52 cards?
You need all combinations of n items from a set of N items (in your case, N == 52, but I'll keep the answer generic).
Each combination can be represented as an array of item indexes, size_t item[n], such that:
0 <= item[i] < N
item[i] < item[i+1], so that each combination is a unique subset.
Start with item[i] = i. Then to iterate to the next combination:
If the final index can be incremented (i.e. item[n-1] < N-1), then do that.
Otherwise, work backwards until you find an index that can be incremented, and still leave room for all the following indexes (i.e. item[n-i] < N-i). Increment that, then reset all the following indexes to the smallest possible values.
If you can't find any index that you can increment (i.e. item[0] == N-n), then you're done.
In code, it might look something vaguely like this (untested):
void first_combination(size_t item[], size_t n)
{
for (size_t i = 0; i < n; ++i) {
item[i] = i;
}
}
bool next_combination(size_t item[], size_t n, size_t N)
{
for (size_t i = 1; i <= n; ++i) {
if (item[n-i] < N-i) {
++item[n-i];
for (size_t j = n-i+1; j < n; ++j) {
item[j] = item[j-1] + 1;
}
return true;
}
}
return false;
}
It might be nice to make it more generic, and to look more like std::next_permutation, but that's the general idea.
This combinations iterator class is derived from the previous answers posted here.
I did some benchmarks and it is a least 3x faster than any next_combination() function you would have used before.
I wrote the code in MetaTrader mql4 to do testing of triangular arbitrage trading in forex. I think you can port it easily to Java or C++.
class CombinationsIterator
{
private:
int input_array[];
int index_array[];
int m_indices; // K
int m_elements; // N
public:
CombinationsIterator(int &src_data[], int k)
{
m_indices = k;
m_elements = ArraySize(src_data);
ArrayCopy(input_array, src_data);
ArrayResize(index_array, m_indices);
// create initial combination (0..k-1)
for (int i = 0; i < m_indices; i++)
{
index_array[i] = i;
}
}
// https://stackoverflow.com/questions/5076695
// bool next_combination(int &item[], int k, int N)
bool advance()
{
int N = m_elements;
for (int i = m_indices - 1; i >= 0; --i)
{
if (index_array[i] < --N)
{
++index_array[i];
for (int j = i + 1; j < m_indices; ++j)
{
index_array[j] = index_array[j - 1] + 1;
}
return true;
}
}
return false;
}
void get(int &items[])
{
// fill items[] from input array
for (int i = 0; i < m_indices; i++)
{
items[i] = input_array[index_array[i]];
}
}
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
// driver program to test above class
#define N 5
#define K 3
void OnStart()
{
int x[N] = {1, 2, 3, 4, 5};
CombinationsIterator comboIt(x, K);
int items[K];
do
{
comboIt.get(items);
printf("%s", ArrayToString(items));
} while (comboIt.advance());
}
Output:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
#include <iostream>
#include <vector>
using namespace std;
class CombinationsIndexArray {
vector<int> index_array;
int last_index;
public:
CombinationsIndexArray(int number_of_things_to_choose_from, int number_of_things_to_choose_in_one_combination) {
last_index = number_of_things_to_choose_from - 1;
for (int i = 0; i < number_of_things_to_choose_in_one_combination; i++) {
index_array.push_back(i);
}
}
int operator[](int i) {
return index_array[i];
}
int size() {
return index_array.size();
}
bool advance() {
int i = index_array.size() - 1;
if (index_array[i] < last_index) {
index_array[i]++;
return true;
} else {
while (i > 0 && index_array[i-1] == index_array[i]-1) {
i--;
}
if (i == 0) {
return false;
} else {
index_array[i-1]++;
while (i < index_array.size()) {
index_array[i] = index_array[i-1]+1;
i++;
}
return true;
}
}
}
};
int main() {
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
a.push_back(5);
int k = 3;
CombinationsIndexArray combos(a.size(), k);
do {
for (int i = 0; i < combos.size(); i++) {
cout << a[combos[i]] << " ";
}
cout << "\n";
} while (combos.advance());
return 0;
}
Output:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
I see this problem is essentially the same as the power set problem. Please see Problems with writing powerset code to get an elegant solution.