Need to make a function that checks if an array is a permutation

Hello all,

I need to create a function with the following prototype:

bool isPermutation( const unsigned a[], unsigned elements );


unsigned a[] = {3, 0, 2, 1};
bool P1 = isPermutation( a, 4 );
would set P1 to true because the set of subscripts is {0, 1, 2, 3}, and the values are just a reordering of those values. On the other hand,

unsigned a[] = {3, 0, 2, 3};
bool P2 = isPermutation( a, 4 );
would set P2 to false because the set of subscripts is {0, 1, 2, 3}, but there’s no value that’s equal to 1.

I'm not exactly sure how to do this. I thought about it a couple different ways. I first thought about taking the range (max/min) and then checking to see if the numbers in between are equal from each other, distance-wise.

I then thought that I should just make this basically a sort function (I used bubble-sort), and then to just check if the numbers are equi-distant from each other.

This is my basic bubble-sort. Perhaps it is wrong, but I'm not certain...Perhaps I am making this function harder than it has to be. Thanks for reading.

1
2
3
4
5
6
7
8
9
10
11
unsigned temp = 0;

for (unsigned i = 0; i < elements; i++){

 for (unsigned k = 0; k < elements-1; k++){

 if (a[k] > a[k+1]){
 temp = a[k+1];
 a[k+1] = a[k];
 a[k] = temp;
 }}}


Should I do a sort like this, and then do something where I subtract a[i+1] - a[i], and see if that equals '1'?. I would think that would mean they would have to be equidistant. Even if this is correct, I feel like it could be more efficient.
Last edited on
1
2
3
4
5
6
for (int i = 0; i < elements; i++){
if (a[i+1] - a[i] == 1){
return true;
}
else return false;
}


This is the last part - Does my logic look correct? I can already see that I will return "true" on the first pass of the loop, and would want it to go through the entire array before it would return "true." Would appreciate the input/suggestions.

Thanks.
Last edited on
You can put them in a set and compare the sets. Or you can sort the arrays and compare those.
Last edited on
Thanks - Also, I know it's an amateurish question, but how would I make sure I'm NOT returning true or false after only one iteration (like I'm doing above)?
Last edited on
how would I make sure I'm NOT returning true or false after only one iteration
Does that code work? I can't see how it can.
Topic archived. No new replies allowed.