Поиск повторяющихся целых чисел в массиве и отображение количества раз, когда они произошли

Я работаю над кодом, который выводит дублированные целые числа из массива с числом их появления. Мне не разрешено использовать LINQ, просто простой код. Я думаю, что я настолько близок, но смущен тем, как получить правильный результат:

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();
        }
    }
}

Ответы

Ответ 1

Поскольку вы не можете использовать LINQ, вы можете сделать это с помощью коллекций и циклов:

static void Main(string[] args)
{              
    int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
    var dict = new Dictionary<int, int>();

    foreach(var value in array)
    {
        if (dict.ContainsKey(value))
            dict[value]++;
        else
            dict[value] = 1;
    }

    foreach(var pair in dict)
        Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
    Console.ReadKey();
}

Ответ 2

Используйте Группировать по:

int[] values = new []{1,2,3,4,5,4,4,3};

var groups = values.GroupBy(v => v);
foreach(var group in groups)
    Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());

Ответ 3

Посмотрим на более простой пример. Пусть говорят, что у нас есть массив {0, 0, 0, 0}.

Что будет делать ваш код?

Сначала вы увидите, сколько элементов после первого элемента равно ему. Есть три элемента после первого, которые равны ему.

Затем он переходит к следующему элементу и ищет все элементы после него, которые равны ему. Есть два. До сих пор мы находимся в 5, и мы еще не закончили (у нас есть еще одна возможность добавить), но во всем массиве всего четыре элемента.

Ясно, что у нас есть проблема. Нам нужно убедиться, что, когда мы искали массив для дубликатов заданного элемента, мы не просматриваем его снова для этого же элемента. Хотя есть способы сделать это, этот фундаментальный подход выглядит довольно много.

Конечно, есть разные подходы, которые мы можем предпринять. Вместо того, чтобы проходить через каждый элемент и искать других, как он, мы можем циклически пройти через массив один раз и добавить к количеству раз, когда мы нашли этот символ. Использование Dictionary делает это проще:

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

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

Теперь мы можем просто прокрутить словарь и посмотреть, какие значения были найдены более одного раза:

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

Это делает код понятным для чтения, очевидно, правильного и (в качестве бонуса) намного более эффективным, чем ваш код, так как вы можете избежать чередования через коллекцию несколько раз.

Ответ 4

Вот ответ, который позволяет избежать использования словарей. Поскольку ОП сказал, что он не знаком с ними, это может дать ему небольшое представление о том, что делают словари.

Недостатком этого ответа является принудительное ограничение максимального количества в массиве, и вы не можете иметь отрицательные числа. Вы никогда не использовали бы эту версию в реальном коде.

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int[] count = new int[13];

foreach(int number in array) {
    // using the index of count same way you'd use a key in a dictionary
    count[number]++;
}

foreach(int c in count) {
    int numberCount = count[c];
    if(numberCount > 0) {
        Console.WriteLine(c + " occurs " + numberCount + " times");
    }
}

Ответ 5

Хорошо, я изменил ваш код. Это должно выполнить эту задачу:

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

Вы сделали небольшую ошибку при использовании J вместо i...

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[i] == array[j+1])
                  count = count + 1;
            }
            Console.WriteLine("\t\n " + array[i] + "occurse" + count);
            Console.ReadKey();
        }
    }
}

Ответ 7

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 7, 7, 8, 9, 7, 12, 12 };
Dictionary<int, int> duplicateNumbers = new Dictionary<int, int>();
int count=1;
for (int i = 0; i < array.Length; i++)
{
    count=1;
    if(!duplicateNumbers.ContainsKey(array[i]))
    {
        for (int j = i; j < array.Length-1; j++)
        {
            if (array[i] == array[j+1])
            {
                count++;                            
            }
        }
        if (count > 1)
        {
            duplicateNumbers.Add(array[i], count);
        }
    }
}
foreach (var num in duplicateNumbers)
{
    Console.WriteLine("Duplicate numbers, NUMBER-{0}, OCCURRENCE- {1}",num.Key,num.Value);
}

Ответ 8

/Это ответ, который поможет вам найти повторяющиеся целочисленные значения, используя Forloop, и он вернет только повторяющиеся значения, кроме времени его появления /

    public static void Main(string[] args)
    {
        //Array list to store all the duplicate values
        int[] ary = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        ArrayList dup = new ArrayList();

        for (int i = 0; i < ary.Length; i++)
        {
            for (int j = i + 1; j < ary.Length; j++)
            {
                if (ary[i].Equals(ary[j]))
                {
                    if (!dup.Contains(ary[i]))
                    {
                        dup.Add(ary[i]);
                    }
                }
            }
        }
        Console.WriteLine("The numbers which duplicates are");
        DisplayArray(dup);
    }
    public static void DisplayArray(ArrayList ary)
    {
        //loop through all the elements
        for (int i = 0; i < ary.Count; i++)
        {
            Console.Write(ary[i] + " ");
        }
        Console.WriteLine();
        Console.ReadKey();
    }

Ответ 9

int[] arr = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
var result = arr.GroupBy(x => x).Select(x => new { key = x.Key, val = x.Count() });       
foreach (var item in result)
{
    if(item.val > 1)
    {                
        Console.WriteLine("Duplicate value : {0}", item.key);
        Console.WriteLine("MaxCount : {0}", item.val);
    }

}

Console.ReadLine();

Ответ 10

Этот подход, исправленный, даст правильный результат (он очень неэффективен, но это не проблема, если вы не увеличиваете масштаб).

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();
}

Я подсчитал 5 ошибок в OP-коде, отмеченных ниже.

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 spelled "occurs" :)
    Console.ReadKey();
}

Изменить

Для лучшего подхода используйте Dictionary для отслеживания отсчетов. Это позволяет вам прокручивать массив только один раз и не печатать повторяющиеся подсчеты на консоль.

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);

Ответ 11

Я согласен с тем, что с помощью Dictionary лучше работать, а затем вложенные for циклы (O (n) vs O (n ^ 2)). Однако, чтобы обратиться к OP, вот решение, в котором используется HashSet, чтобы предотвратить повторение подсчета уже отсчитанных чисел, таких как целое число 5 в массиве примеров.

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

    var set = new HashSet<int>();
    for (int i = 0; i < A.Length - 1; i++) {
        int count = 0;
        for (int j = i; j < A.Length - 1; j++) {
            if (A[i] == A[j + 1] && !set.Contains(A[i]))
                count++;
        }
        set.Add(A[i]);
        if (count > 0) {
            Console.WriteLine("{0} occurs {1} times", A[i], count + 1);
            Console.ReadKey();
        }
    }
}

Ответ 12

public static void Main (string [] args)

{

Int [] array = {10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12};

List<int> doneNumbers = new List<int>();


for (int i = 0; i < array.Length - 1; i++)

{

    if(!doneNumbers.Contains(array[i]))

    {

        int currentNumber = array[i];

        int count = 0;

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

        {

            if(currentNumber == array[j])

            {

                count++;

            }

        }

        Console.WriteLine("\t\n " + currentNumber +" "+ " occurs " + " "+count + " "+" times");

        doneNumbers.Add(currentNumber);

        Console.ReadKey();
      }

   }

}

}

}

Ответ 13

//Этот метод подсчитывает общее количество повторяющихся элементов в массиве

public void DuplicateElementsInArray(int[] numbers)
    {
        int count = 0;

        for (int i = 0; i < numbers.Length; i++)
        {

            for (int j = i; j < numbers.Length - 1; j++)
            {
                if (numbers[i] == numbers[j+1])
                {                       
                    count++;
                    break;
                }                       
            }               
        }
        Console.WriteLine("Total number of duplicate elements found in the array is: {0}", count);
    }

Ответ 14

Просто используйте код ниже, не нужно использовать словарь или ArrayList.Hope это помогает:)

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

                if(array[i] == array[j])
                {
                    count++;
                    k=j-1;
                }
                else break;
        }
        Console.WriteLine("\t\n " + array[i] + "---------->" + count);            
        if(k!=-1)
            i=k+1;          
    }
}

Ответ 15

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);
    }
}

Ответ 16

 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();

    }
}

Ответ 17

int copt = 1;
int element = 0;
int[] array = { 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5 };
for (int i = 0; i < array.Length; i++)
{
   for (int j = i + 1; j < array.Length - 1; j++)
   {
       if (array[i] == array[j])
       {
          element = array[i];
          copt++;
          break;
       }
   }
}

Console.WriteLine("the repeat element is {0} and it appears {1} times ", element, copt);
Console.ReadKey();

//вывод элемента 3 и появляется 9 раз

Ответ 18

 class Program
{
    static void Main(string[] args)
    {
        int[] arr = { 2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12 };
        List<int> nums = new List<int>();
        List<int> count = new List<int>();
        nums.Add(arr[0]);
        count.Add(1);
        for (int i = 1; i < arr.Length; i++)
        {

            if(nums.Contains(arr[i]))
            {
                count[nums.IndexOf(arr[i])] += 1;
            }
            else
            {
                nums.Add(arr[i]);
                count.Add(1);
            }
        }

        for(int x =0; x<nums.Count;x++)
        {
            Console.WriteLine("number:"+nums[x] +"Count :"+ count[x]);
        }
        Console.Read();
    }
}

Ответ 19

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    /// <summary>
    /// How do you find the duplicate number on a given integer array?
    /// </summary>
    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 };

            Dictionary<int, int> duplicates = FindDuplicate(array);

            Display(duplicates);

            Console.ReadLine();
        }

        private static Dictionary<T, int> FindDuplicate<T>(IEnumerable<T> source)
        {
            HashSet<T> set = new HashSet<T>();
            Dictionary<T, int> duplicates = new Dictionary<T, int>();

            foreach (var item in source)
            {
                if (!set.Add(item))
                {
                    if (duplicates.ContainsKey(item))
                    {
                        duplicates[item]++;
                    }
                    else
                    {
                        duplicates.Add(item, 2);
                    }
                }
            }

            return duplicates;
        }

        private static void Display(Dictionary<int, int> duplicates)
        {
            foreach (var item in duplicates)
            {
                Console.WriteLine($"{item.Key}:{item.Value}");
            }
        }
    }
}

Ответ 20

static void printRepeating (int [] arr,                           в размер)   {       int i;

    Console.Write("The repeating" +  
                   " elements are : "); 

    for (i = 0; i < size; i++) 
    { 
        if (arr[ Math.Abs(arr[i])] >= 0) 
            arr[ Math.Abs(arr[i])] = 
                -arr[ Math.Abs(arr[i])]; 
        else
            Console.Write(Math.Abs(arr[i]) + " "); 
    }          
}  

Ответ 21

Вы можете проверить следующие коды. Коды работают.

 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 + 1; j < array.Length; j++) {

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

Ответ 22

Использовать 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 возвращает структуру данных, которая позволяет индексировать. Это метод расширения. Мы получаем экземпляр ILookup, который можно индексировать или перечислять, используя foreach -loop. Записи объединяются в группы по каждому ключу.