Function which returns a sorted array without duplicates
Salih Dincer
salihdb at hotmail.com
Mon Jan 23 05:12:41 UTC 2023
On Sunday, 22 January 2023 at 23:26:45 UTC, dan wrote:
>
> So what i was missing was std.array.
Of course you can use the uniq from Phobos. But since we already
use array, you should also try the 3rd classic version:
```d
import std.algorithm;
import std.array;
// qef. version:
private S[] sortArray ( S )( S[] x )
{
auto y = x.dup;
return y.sort.uniq.array;
}
// no dup. version:
private S[] sortArrayy ( S )( S[] x )
{
S[] w;
foreach ( v ; x ) w ~= v;
return w.sort.uniq.array;
}
// classic version:
private S[] sortArrayyy ( S )( S[] x )
{
S[] w = x.dup;
w.sort;
size_t diff;
for (size_t j, i = 1; i < w.length; ++i) {
if (w[j] != w[i]) {
w[++j] = w[i];
} else {
++diff;
}
}
return w[0 .. $ - diff];
}
void main()
{
uint[] nums = [1, 3, 2, 5, 1, 4, 2, 8];
auto sorted = nums.sortArray;
assert(sorted.equal(nums.sortArrayy));
assert(sorted.equal(nums.sortArrayyy));
import std.stdio;
writeln( "Input: ", nums );
writeln( "Output: ", sorted );
}
```
In fine, we have implemented 3 ways to sort an array and return
it without repetition. I guess, there is no alternative to this
basic algorithm...
SDB at 79
More information about the Digitalmars-d-learn
mailing list