Finding duplicate integers in an array and display

2019-01-17 15:55发布

I'm working on a code that prints out duplicated integers from an array with the number of their occurrence. I'm not allowed to use LINQ, just a simple code. I think I'm so close but confused about how to get a correct output:

class Program
{
    static void Main(string[] args)
    {              
        int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        int count = 1;
        for (int i = 0; i < array.Length; i++)
        {
            for (int j = i; j < array.Length - 1 ; j++)
            {

               if(array[j] == array[j+1])
                  count = count + 1;
            }
            Console.WriteLine("\t\n " + array[i] + "occurse" + count);
            Console.ReadKey();
        }
    }
}

17条回答
爷、活的狠高调
2楼-- · 2019-01-17 16:13
public class Program
{
    public static void Main(string[] args)
    {
        int[] arr = new int[]{10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12};

        int numberOfDuplicate = 0;
        int arrayLength = arr.Length;

        for(int i=0; i < arrayLength; i++)  
        {  
           for(int j = 1; j < arrayLength; j++)  
           {
               if(j < i && arr[j]==arr[i])
               {
                  break; 
               }
               else if(i != j && arr[i]==arr[j])
               {
                  Console.Write("duplicate : arr[{0}]={1}--arr[{2}]={3}\n",i,arr[i],j,arr[j]);
                  numberOfDuplicate++;
                  break;
               }
           }
        }

        Console.Write("Total duplicate element in an array 'arr' is {0}\n ",numberOfDuplicate);
    }
}
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-17 16:14

Use ToLookup:

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
var result = values.ToLookup(v => v).Select(x=>new {Value=x.Key,Count=x.Count() });

ToLookup returns a data structure that allows indexing. It is an extension method. We get an ILookup instance that can be indexed or enumerated using a foreach-loop. The entries are combined into groupings at each key.

查看更多
Ridiculous、
4楼-- · 2019-01-17 16:15

Let's take a look at a simpler example. Let's say we have the array {0, 0, 0, 0}.

What will your code do?

It will first look to see how many items after the first item are equal to it. There are three items after the first that are equal to it.

Then it goes to the next item, and looks for all items after it that are equal to it. There are two. So far we're at 5, and we haven't even finished yet (we have one more to add), but there are only four items in the whole array.

Clearly we have an issue here. We need to ensure that when we've searched the array for duplicates of a given item that we don't search through it again for that same item. While there are ways of doing that, this fundamental approach is looking to be quite a lot of work.

Of course, there are different approaches entirely that we can take. Rather that going through each item and searching for others like it, we can loop through the array once, and add to a count of number of times we've found that character. The use of a Dictionary makes this easy:

var dictionary = new Dictionary<int, int>();

foreach (int n in array)
{
    if (!dictionary.ContainsKey(n))
        dictionary[n] = 0;
    dictionary[n]++;
}

Now we can just loop through the dictionary and see which values were found more than once:

foreach(var pair in dictionary)
    if(pair.Value > 1)
        Console.WriteLine(pair.Key);

This makes the code clear to read, obviously correct, and (as a bonus) quite a lot more efficient than your code, as you can avoid looping through the collection multiple times.

查看更多
Explosion°爆炸
5楼-- · 2019-01-17 16:16

Ok I have modified your code. This should do the job:

class Program
{
    static void Main(string[] args)
    {
        int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };

        for (int i = 0; i < array.Length; i++)
        {
            int count = 0;
            for (int j = 0; j < array.Length; j++)
            {

                if (array[i] == array[j])
                    count = count + 1;
            }
            Console.WriteLine("\t\n " + array[i] + " occurs " + count + " times");
        }
        Console.ReadKey();
    }
}
查看更多
放我归山
6楼-- · 2019-01-17 16:21
 class Program
{
    static void Main(string[] args)
    {
        int[] arr = new int[] { 10, 20,20, 30, 10, 50 ,50,9};
        List<int> listadd = new List<int>();

        for (int i=0; i <arr.Length;i++)
        {
           int count = 0;
            int flag = 0;

            for(int j=0; j < arr.Length; j++)
            {
                if (listadd.Contains(arr[i]) == false)
                {


                    if (arr[i] == arr[j])
                    {
                        count++;
                    }

                } 

                else
                {
                    flag = 1;
                }

            }
            listadd.Add(arr[i]);
            if(flag!=1)
            Console.WriteLine("No of occurance {0} \t{1}", arr[i], count);
        }
        Console.ReadLine();

    }
}
查看更多
Explosion°爆炸
7楼-- · 2019-01-17 16:22

This approach, fixed up, will give the correct output (it's highly inefficient, but that's not a problem unless you're scaling up dramatically.)

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
    int count = 0;
    for (int j = 0; j < array.Length ; j++)
    {
       if(array[i] == array[j])
          count = count + 1;
    }
    Console.WriteLine("\t\n " + array[i] + " occurs " + count);
    Console.ReadKey();
}

I counted 5 errors in the OP code, noted below.

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1;                                   // 1. have to put "count" in the inner loop so it gets reset
                                                 // 2. have to start count at 0
for (int i = 0; i < array.Length; i++)
{
    for (int j = i; j < array.Length - 1 ; j++)  // 3. have to cover the entire loop
                                                 // for (int j=0 ; j<array.Length ; j++)
    {
       if(array[j] == array[j+1])                // 4. compare outer to inner loop values
                                                 // if (array[i] == array[j])
          count = count + 1;
    }
    Console.WriteLine("\t\n " + array[i] + "occurse" + count);
                                                 // 5. It's spelled "occurs" :)
    Console.ReadKey();
}

Edit

For a better approach, use a Dictionary to keep track of the counts. This allows you to loop through the array just once, and doesn't print duplicate counts to the console.

var counts = new Dictionary<int, int>();
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
    int currentVal = array[i];
    if (counts.ContainsKey(currentVal))
        counts[currentVal]++;
    else
        counts[currentVal] = 1;
}
foreach (var kvp in counts)
    Console.WriteLine("\t\n " + kvp.Key + " occurs " + kvp.Value);
查看更多
登录 后发表回答