-1

The code only removes duplicates apart from the last 2 of any number

for (int i = 0; i < primeNumbers.Count; i = i + 1)
{
   for (int j = i + 1; j < primeNumbers.Count; j = j + 1)
   {
      if (primeNumbers[i] == primeNumbers[j])
      {
          primeNumbers.RemoveAt(j); 
         

      }
   }
}

for (int i = 0; i < primeNumbers.Count; i++)
    Console.WriteLine(primeNumbers[i]);

4 Answers4

3

To improve time complexity, use a Set. A Set cannot have duplicates. Just iterate once through your list, and add each value to the set.

Complexity will be linear O(n).

0xRyN
  • 852
  • 2
  • 13
  • I'm sorry my question is too remove from an existing list of numbers, not too add and not include. My solution right now isn't quite working – Ibrahim Rizwan Sep 11 '22 at 17:54
  • I know. But it's more effecient to create a Set and to remove duplicates this way, and then to copy the set to a list. – 0xRyN Sep 11 '22 at 17:56
0

this is simple and elegant:

const noDupes = primeNumbers.filter((item, ind, arr) => ind === arr.indexOf(item));

HTH

Igor Micev
  • 1,514
  • 1
  • 17
  • 23
0

Your inner for loop will skip the next entry after the remove. After the remove, decrement j so that it will recheck the current entry on the next loop.

So add j--;

Bob Vale
  • 18,094
  • 1
  • 42
  • 49
0

I would use the following code to improve:

If your primeNumbers is an Array[]:

primeNumbers = primeNumbers.Distinct().ToArray();

If your primeNumbers is an List<>:

primeNumbers = primeNumbers.Distinct().ToList();

If your primeNumbers is an HashSet<>:

primeNumbers = primeNumbers.Distinct().ToHashSet();

EXTRA When filling up your list of primenumbers, use HashSet

HashSet primeNumbers = new();
primeNumbers.Add(number);

It will automatically remove the duplicates.

This collection is introduced in . NET 3.5.

  • yea im using a list :), so how would i implement this hashset? – Ibrahim Rizwan Sep 11 '22 at 18:35
  • If you use a list already, simply call yourlist.Distinct(); In case you want HashSet, replace your List with HashSet (declaration or primenumbers) Adding the numbers t a list and HashSet is the same, with the . Add method – Frederik van Lierde Sep 11 '22 at 20:31