std::next_permutation missing one entry - c++

Following program is missing one permutation entry.
#include <iostream>
#include <vector>
#include <algorithm>
int main ( int argc, char **argv) {
std::vector<int> temp;
temp.push_back(10);
temp.push_back(2);
temp.push_back(4);
temp.push_back(4);
do {
std::copy(temp.begin(),temp.end(),std::ostream_iterator<int>(std::cout," "));
std::cout << std::endl;
}while ( std::next_permutation (temp.begin(), temp.end()));
}
Following is the output of the program
10 2 4 4
10 4 2 4
10 4 4 2
why it is missing one entry which is
2 4 4 10

This is because that permutation is the first ordering for the list of number that you have.
You would need to sort the original array, then this permutation will be listed as the very first one.
std::vector<int> temp;
temp.push_back(10);
temp.push_back(2);
temp.push_back(4);
temp.push_back(4);
std::sort(temp.begin(),temp.end() );
Alternatively, you could just push the elements in sorted order, but for practical purposes, you should always sort if you want to generate all possible permutations.

It's actually missing a few other valid permutations: 2 10 4 4 and 2 4 10 4, and 4 4 10 2 for example.
As to why they are missing: it says, right there in the documentation:
Return value
true if the function could rearrange the object as a lexicographically greater permutation. Otherwise, the function returns false to indicate that the arrangement is not greater than the previous, but the lowest possible (sorted in ascending order).
So the while loop ends after 10 4 4 2, because that is the lexicographically greatest permutation (the one that's "biggest" when you compare them left-to-right, i.e. the one that's in descending order). After printing that one, next_permutation fails to get to the 'next' permutation, and wraps around to the "beginning" permutation of 2 4 4 10; but that is not printed because the function also returned false.

Related

Why using std::sort() ) gives me garbage values?

I was trying to solve a problem where I had to sort so I used the standard library std::sort function but I get a wrong output in the 2nd test case:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,i;
cin>>n;
int arr[n-1];
for(i=1;i<=n-1;i++)
cin>>arr[i];
int size=sizeof(arr)/sizeof(arr[1]);
sort(arr,arr+size);
for(i=1;i<=n-1;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
return 0;
}
I/P:
2
5
1 2 5 4
10
1 2 3 4 5 6 7 8 10
Expected O/P:
1 2 4 5
1 2 3 4 5 6 7 8 10
Actual O/P:
1 2 4 5
2 3 4 5 6 7 8 2013562 10
First of all, int arr[n-1]; is a variable length array. That's not actually part of C++, even though some compilers will tolerate it nevertheless. In most cases you can just use std::vector<int>(n-1); instead.
But look at this loop:
for(i=1;i<=n-1;i++)
cin>>arr[i];
You're starting at 1 and got all the way up to n-1, however your array goes from arr[0] to arr[n-2]. So you got undefined behavior because you're writing one past the size of the array, and you also don't write to the first position (leading to more undefined behavior when you try to sort with this uninitialized value still present).
Instead, the loop should be for(i=0;i<n-1;i++) The same applies to where you're printing it. You can then sort the vector this way:
sort(arr.begin(), arr.end());
Also note that by doing n-1 you're always reading in and handling one less value that the user inputs, I'm not sure if that's your intention. If you want that, you could also just decrease n by one after reading it in instead of writing n-1 in multiple places.

How to count the number of permutations?

We are given array-'a' and array-'b' consisting of positive integers.
How can I count all the permutation of array 'a' which are strictly lexicographically smaller than array-'b'?
Arrays can contain as many as 10^5 integers(positive)
Example:
1 2 3 is lexicographically smaller than 3 1 2
1 2 3 is lexicographically smaller than 1 4 5.
I would like the solution to be in C++.
Input : 3
1 2 3
2 1 3
Output : 2
Only permutations 1,2,3 and 1,3,2 are lexicographically smaller than 2 1 3
Let's just tackle the algorithm. Once you get that figured out, the implementation should be pretty straightforward. Does this look like it does what you're looking for?
Pseudo code:
function get_perms(a,b)
#count the number of digits in a that are <b[0]
count = sum(a<b[0])
Nperms = (len(a)-1)! #modify this formula as needed
N = count*Nperms
if sum(a==b[0]) > 0
remove 1 b[0] from a
# repeat the process with the substring assuming a[0]==b[0]
N += sum(a==b[0])*get_perms(a,b[1:end])
return N
main()
get_perms(a,b)
Edit: I did a little searching. I believe that this is what you are looking for.

vector erase specific indexes with iterators (not based on range or condition)

Say, I have two vector as follows in the code, I want to erase the elements indexed by vector "index_to_filter" in the vector "data" using iterators. The dummy way in the code is just to point the obvious error. So far, I couldn't get it working, nor, figured out if this could be an erase-remove-idiom?. Is there a way to and am missing it ?
Thx.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> data{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int> index_to_filter{ 1, 5, 8 };
/* needed result data = { 0, 2, 3, 4, 6, 7, 9 }*/
std::vector<int>::iterator iter = index_to_filter.begin();
while (iter != index_to_filter.end())
{
std::vector<int>::iterator iter_data = data.begin() + *iter;
iter_data = data.erase(iter_data);
iter++;
}
/* Throws : vector erase iterator outside range */
for (int i: data)
std::cout << i << std::endl;
system("pause");
return 0;
}
PS: the vector.erase question is aborded tens of times here but found no clue for this one !
PS: Solutions without iterators are not welcome. (No offense !)
thanks
Your problem is very simple:
std::vector<int> index_to_filter{ 1, 5, 8 };
You intent is to remove elements #1, #5, and #8 from the other array, and you start with element #1:
Value 0 1 2 3 4 5 6 7 8 9
Index 0 1 2 3 4 5 6 7 8 9
^ ^ ^
The bottom line, the "index" line, is the index into the vector. The top line, the "value" line, is the value in that position in the vector. When you start, the two values are the same.
The carets mark the indexes you wish to remove, and you start with element #1.
The fundamental gap that you are ignoring is that when you remove an element from the vector, you do not exactly have a gaping black hole, a void in that position. All subsequent values in the container shift over. So, when you remove element #1, the remaining values shift over:
Value 0 2 3 4 5 6 7 8 9
Index 0 1 2 3 4 5 6 7 8
^ ^
The next element you wish to remove is element #5. Unfortunately, the value at that position in the vector is no longer 5. It is 6, because the array has shifted. Your code than proceeds and removes index position #5, which has the following result:
Value 0 2 3 4 5 7 8 9
Index 0 1 2 3 4 5 6 7
^
You have already gone off the rails here. But now, your code attempts to remove index #8, which no longer exists, since the vector is now shorter. As soon as your code attempts to do that, you blow up.
So, in conclusion: what you're missing is the simple fact that removing a value from a middle of a vector shifts all subsequent values up by one position, in order to fill the gap left from the removed element, and the code you wrote fails to account for that.
The simplest solution is to remove elements from the highest index position to the lowest. In your code, you already have index_to_filter in sorted order, so instead of iterating from the beginning of index_to_filter to its end, from the lowest to the highest index, iterate backwards, from the last index in index_to_filter to the first, so your code attempts to remove indexes 8, 5, then 1, so that each time the removal of the element does not affect the lower index positions.
If index_to_filter is guaranteed to be sorted, you should be able to just remove the elements in reverse order - the index to filter is still correct as long as no previous entries have been removed.
So just call index_to_filter.rbegin() and index_to_filter.rend() in your current code.

finding the common elements of vectors which are inside another map

dear all,
i have a map, defined as map<int, vector<int> > my_map. So, for example it looks like as follows,
my_map=
0 1 2 6 5 4
1 0 2 3 4 5
2 0 1 4
3 1
4 1 2 0 7 5 6
5 1 0 6 4
6 0 5 4
7 4
vector<int> element_common(map<int, vector<int> > &my_map, int s1, int s2){
vector<int> common2;
vector<int> first_vector=my_map[s1];
vector<int>::iterator snd_vector_begin= my_map[s2].begin();
vector<int>::iterator snd_vector_end= my_map[s2].end();
for (vector<int>::iterator any=first_vector.begin();
any!=first_vector.end();
any++){
// check if any is in other_list
vector<int>::iterator any_in_snd_vector_iterator= find (snd_vector_begin,snd_vector_end, *any);
if(any_in_snd_vector_iterator==snd_vector_end){
common2.push_back(*any);
}
}
return common2;
i wrote a function above function to get common elements from the vector parts which are relevant to 2 given keys. when keys are equal to s1 and s2, i.e. s1=1 and s2=4. then my function should give me 0,2,5. but i got 3,4. please help me to rectify my function.
If you can guarantee your vectors are sorted then you can improve your performance substantially from O(mn) to O(m + n):
std::vector<int> common;
std::set_intersection(vec1.begin(), vec1.end(),
vec2.begin(), vec2.end(),
std::back_inserter(common));
You got the test exactly backwards:
if(any_in_2nd_vector_iterator==2nd_vector_end){
is true when the element ISN'T FOUND in the second vector. Try !=.
Then, you can avoid needless copying of vectors by using a reference:
const vector<int>& first_vector=my_map[s1];
and if your vectors get much larger, it may be faster to do a hash lookup (or pre-sorted merge if the vectors are always kept sorted) instead of a call to find which has to check every element.

Permutations with some fixed numbers

How to effectively generate permutations of a number (or chars in word), if i need some char/digit on specified place?
e.g. Generate all numbers with digit 3 at second place from the beginning and digit 1 at second place from the end of the number. Each digit in number has to be unique and you can choose only from digits 1-5.
4 3 2 1 5
4 3 5 1 2
2 3 4 1 5
2 3 5 1 4
5 3 2 1 4
5 3 4 1 2
I know there's a next_permutation function, so i can prepare an array with numbers {4, 2, 5} and post this in cycle to this function, but how to handle the fixed positions?
Generate all permutations of 2 4 5 and insert 3 and 1 in your output routine. Just remember the positions were they have to be:
int perm[3] = {2, 4, 5};
const int N = sizeof(perm) / sizeof(int);
std::map<int,int> fixed; // note: zero-indexed
fixed[1] = 3;
fixed[3] = 1;
do {
for (int i=0, j=0; i<5; i++)
if (fixed.find(i) != fixed.end())
std::cout << " " << fixed[i];
else
std::cout << " " << perm[j++];
std::cout << std::endl;
} while (std::next_permutation(perm, perm + N));
outputs
2 3 4 1 5
2 3 5 1 4
4 3 2 1 5
4 3 5 1 2
5 3 2 1 4
5 3 4 1 2
I've read the other answers and I believe they are better than mine for your specific problem. However I'm answering in case someone needs a generalized solution to your problem.
I recently needed to generate all permutations of the 3 separate continuous ranges [first1, last1) + [first2, last2) + [first3, last3). This corresponds to your case with all three ranges being of length 1 and separated by only 1 element. In my case the only restriction is that distance(first3, last3) >= distance(first1, last1) + distance(first2, last2) (which I'm sure could be relaxed with more computational expense).
My application was to generate each unique permutation but not its reverse. The code is here:
http://howardhinnant.github.io/combinations.html
And the specific applicable function is combine_discontinuous3 (which creates combinations), and its use in reversible_permutation::operator() which creates the permutations.
This isn't a ready-made packaged solution to your problem. But it is a tool set that could be used to solve generalizations of your problem. Again, for your exact simple problem, I recommend the simpler solutions others have already offered.
Remember at which places you want your fixed numbers. Remove them from the array.
Generate permutations as usual. After every permutation, insert your fixed numbers to the spots where they should appear, and output.
If you have a set of digits {4,3,2,1,5} and you know that 3 and 1 will not be permutated, then you can take them out of the set and just generate a powerset for {4, 2, 5}. All you have to do after that is just insert 1 and 3 in their respective positions for each set in the power set.
I posted a similar question and in there you can see the code for a powerset.