Here is another solution, using STL algorithm functions:
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
bool g(int *t, int n)
{
if ( n == 0 )
return false;
std::sort(t, t + n);
return (t[0] == 1) && // first number must be 1
(std::distance(t, std::unique(t, t + n)) == n) && // all must be unique
(std::accumulate(t, t + n, 0) == (n * (n + 1)) / 2); // has to add up correctly
}
int main()
{
int arr[] = {1,2,3,4,5,6,7};
std::cout << g(arr, 7);
}
Live Example
After sorting the list of number, the std::unique
algorithm function is used to move the non-unique items to the end of the array, and then give us a pointer to the start of this sequence of non-unique items. If all the values are unique, then std::unique
will return one position past the end of the array.
That is the reason for std::distance
-- it tells us if the number of numbers between the beginning and the start of the non-unique sequence is equal to the number of numbers in the entire list.
The std::accumulate
simply adds up all the numbers in the sequence, and sees if the result is (n * (n+1)) / 2
, which is the classic formula to find the sum of the first n
consecutive integers (starting from 1).
Here is an even shorter solution:
#include <iostream>
#include <algorithm>
using namespace std;
bool g(int *t, int n)
{
if ( n == 0 )
return false;
std::sort(t, t + n);
return (t[0] == 1) && // first number must be 1
(t[n-1] == n) && // last must be n
(std::distance(t, std::unique(t, t + n)) == n); // all must be unique
}
Yet another approach:
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
bool g(int *t, int n)
{
if ( n == 0 )
return false;
std::sort(t, t + n);
return (t[0] == 1) && // first number must be 1
(t[n-1] == n) && // last must be n
(std::set<int>(t, t+n).size() == n); // all must be unique
}
int main()
{
int arr[] = {1,2,3,4,5,6,7};
std::cout << g(arr, 7);
}
Live Example
In this approach, a temporary std::set
is created from the list of numbers. Since a std::set
only stores unique numbers, the size()
of the set after inserting all the items must be equal to n
to determine if all the numbers are unique.