سؤال

Here is the code. It's just deleting the half of duplicate elements from an array and others are to remain there. don't know what is the problem. need assistance thank you.

 int[] count_list = { 10, 20, 10, 30, 30, 40, 20, 50, 90, 60, 80, 70, 80, 90 };
 int l = count_list.Length;   
 for (int i = 0; i < l; i++)
 {
      for (int j =i + 1; j < l;)
      {
           if(count_list[j] == count_list[i]){
                for (int k = j; k < l; k++)
                {
                     count_list[k] = count_list[k + 1] ;
                     l--;
                }

           }
           else{
                j++;
           }
      }       
 }

 for (int i = 0; i < count_list.Length; i++)
 {
      Console.WriteLine(count_list[i]);
      //  Console.WriteLine("name");
 }
هل كانت مفيدة؟

المحلول

The problem is that you're decrementing l with each iteration inner-most for-loop. Try rewriting it like this:

for (int i = 0; i < l; i++)
{
    for (int j = i + 1; j < l;)
    {
        if(count_list[j] == count_list[i]){
            l--;
            for (int k = j; k < l; k++)
            {
                count_list[k] = count_list[k + 1] ;
            }
            break;
        }
        else{
            j++;
        }
    }
}

And remember to call Resize if you want to shrink the array back down at the end:

Array.Resize(ref count_list, l);

However, this is a lot of unnecessary work. I'd strongly suggest using a HashSet<T> or Linq's Distinct extension method:

count_list = count_list.Distinct().ToArray();

نصائح أخرى

You can just use the Distinct method to produce a new array without duplicates;

int[] noDupes = count_list.Distinct().ToArray();

You could use the Distinct method instead:

var newArray = oldArray.Distinct().ToArray();

This will obviously create a new array, instead of editing the original one.

Original answer

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top