Last active
July 13, 2023 21:36
-
-
Save kristiker/5bcd36b2ce8a591c9775a79923a3ae37 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Remove duplicate values from an array | |
// | |
Span<int> nums = new int[] { 0, 0, 6, 1, 2, 4, 6, 5, 2, 1, 0}; | |
Span<T> remove_dupes<T>(Span<T> nums) where T : IEquatable<T> | |
{ | |
int unique_cursor = 0; | |
for (int i = 0; i < nums.Length; i++) | |
{ | |
for (int j = 0; j < nums.Length; j++) | |
{ | |
if (i != j && nums[i].Equals(nums[j])) | |
{ | |
// Was not unique | |
goto NEXT_UP; | |
} | |
} | |
T unique = nums[i]; | |
// Cursor will diverge from i if a dupe is found. | |
if (unique_cursor != i) | |
{ | |
// Swap dupe with unique. Uniques left, dupes right. | |
nums[i] = nums[unique_cursor]; | |
} | |
nums[unique_cursor] = unique; | |
unique_cursor++; | |
NEXT_UP: | |
continue; | |
} | |
return nums[..unique_cursor]; | |
} | |
Console.WriteLine(string.Join(", ", nums.ToArray())); | |
Console.WriteLine(string.Join(", ", remove_dupes(nums).ToArray())); | |
// Output: | |
// 0, 0, 6, 1, 2, 4, 6, 5, 2, 1, 0 | |
// 4, 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment