How to check an array for duplicate elements and replace them with unique ones?
- fourWhy "check" if you can immediately generate random non-repeating elements? - Athari
- @BOPOH Well, yes, I replaced "iterate over all permutations of the sequence of elements and find a relocation in which the elements go in order" to "sort" ... - Athari
- @ Alexander in the loop will be an IndexOutOfRangeException because i + 1 is greater than the index of the last element of the array - david_I
- @david_I, and it is necessary to replace all repeating elements or all but the very first one? Those. there are two elements in the array: [2, 2] - do you need to change it to [1,3] or can you replace it with [2, 1]? If you change all the elements, what will happen if I get an array [1, 3, 2, 4] from the array [2, 2, 3, 3]? Those. Replaced all duplicate elements, but at the same time replaced with other repetitive elements (which, however, now occur only once)? - BOPOH
- @Discord, no, not like that. “sort” would be the solution, since sorting you would find such a permutation automatically. But here the problem is different: it is necessary for the given element X to check that this X has not previously been encountered. Those. This is required to be performed both in the source and in your problem - BOPOH
|
2 answers
If it really doesn’t matter how to replace duplicates, then you can generate a source of elements that are not in the array. Then go through the array, remembering the visited elements, and replacing duplicates. Like that:
int[] arr = new int[] { 1, 3, 2, 1, 5, 7, 3, 2 }; var newElementsSource = Enumerable.Range(0, arr.Length * 2) .Except(arr).GetEnumerator(); HashSet<int> knownElements = new HashSet<int>(); for (int i = 0; i < arr.Length; i++) { int el = arr[i]; if (!knownElements.Add(el)) { arr[i] = newElementsSource.Current; newElementsSource.MoveNext(); } Console.WriteLine(arr[i]); }
- Thank you for help - david_I
|
How to check an array for duplicate elements and replace them with unique ones?
It often happens that arrays cannot be used. For example, if there are several billion numbers in a file that need to be processed, then when you try to create an array, you get an OutOfMemoryException.
In this situation, it is better to define the method as follows:
using System.Collections.Generic; static IEnumerable<int> Random(IEnumerable<int> arr) { var s = new HashSet<int>(); var r = new Random(); foreach (var iv in arr) { var v = iv; while (s.Contains(v)) v = r.Next(0, 1000); // возвращает одно из чисел от 0 до 1000 s.Add(v); yield return v; } } Random(new[] { 1, 2, 3, 1, 2 }); // результат: { 1, 2, 3, 458, 781 }
|