我正在编写一个代码,用于打印出数组中重复的整数及其出现次数。我不允许使用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();
}
}
}
答案 0 :(得分:49)
由于您无法使用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();
}
答案 1 :(得分:15)
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());
答案 2 :(得分:6)
让我们看一个更简单的例子。假设我们有数组{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);
这使代码清晰可读,显然正确,并且(作为奖励)比代码更有效,因为您可以避免多次循环遍历集合。
答案 3 :(得分:3)
好的我已经修改了你的代码。这应该做的工作:
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();
}
}
答案 4 :(得分:3)
这是一个避免使用词典的答案。由于OP说他不熟悉它们,这可能会让他对词典的作用有所了解。
这个答案的缺点是你必须对数组中的最大数量加强限制,而你不能有负数。你真的不会在实际代码中使用这个版本。
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 :(得分:1)
你犯了一个小错误,就是用J代替我......
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();
}
}
}
答案 6 :(得分:1)
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();
答案 7 :(得分:1)
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 :(得分:1)
/ 这是帮助您使用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 :(得分:0)
//此方法计算数组中重复元素的总数
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);
}
答案 10 :(得分:0)
static void printRepeating(int [] arr, 整数大小) { 我
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]) + " ");
}
}
答案 11 :(得分:0)
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}");
}
}
}
}
答案 12 :(得分:0)
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();
}
}
答案 13 :(得分:0)
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's appears {1} times ", element, copt);
Console.ReadKey();
//输出的元素是3,出现9次
答案 14 :(得分:0)
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();
}
}
答案 15 :(得分:0)
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 :(得分:0)
只需使用下面的代码,无需使用字典或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;
}
}
答案 17 :(得分:0)
public static void Main(string [] args)
{
Int [] array = {10,5,10,2,3,3,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();
}
}
}
}
}
答案 18 :(得分:0)
我同意使用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();
}
}
}
答案 19 :(得分:0)
这种修正的方法会给出正确的输出(效率非常低,但除非你大幅度扩大,否则这不是问题。)
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();
}
我在OP代码中计算了5个错误,如下所示。
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();
}
修改
要获得更好的方法,请使用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);
答案 20 :(得分:-1)
使用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
循环进行索引或枚举。这些条目在每个键处组合在一起。
答案 21 :(得分:-1)
您可以查看以下代码。代码正在运作。
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();
}
}
}