Print repeated numbers only one time in c#
I have an array with "n" numbers and I need to print开发者_如何转开发 all repeated numbers only one time
i made this code, but something is wrong
for (int i = 0; i < numbers.Length; i++)
{
for (int j = 1; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j] && i!=j)
{
Console.WriteLine(numbers[i]);
break;
}
}
}
then if my array have the elements {2,3,1,5,2,3}
the program prints :
2
3
3
what can I do?
You can use:
using System.Linq;
…
foreach(var number in numbers.Distinct()) Console.WriteLine(number);
edit
I may have misunderstood the requirement. If you only want to output the numbers that appear more than once, then you can use:
foreach(var group in numbers.GroupBy(n => n).Where(g => g.Count() > 1))
Console.WriteLine(group.Key);
var query = numbers.GroupBy(x => x)
.Where(g => g.Skip(1).Any())
.Select(g => g.Key);
foreach (int n in query)
{
Console.WriteLine(n);
}
Or, alternatively...
var dict = new Dictionary<int, int>();
foreach (int n in numbers)
{
int count;
dict.TryGetValue(n, out count);
if (count == 1)
{
Console.WriteLine(n);
}
dict[n] = count + 1;
}
The problem in your code: you get 3 repeated because when i is 1 (looking at the first 3
) there's another 3 in the list at the end, and when i is 5 (looking at the last 3
) there's another three in the list near the beginning.
Instead you should look at only those numbers which come after your current position - change to int j = i;
so that you only look at the positions after your current position, and you won't get repeated results.
for (int i = 0; i < numbers.Length; i++)
{
for (int j = i; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j] && i!=j)
{
Console.WriteLine(numbers[i]);
break;
}
}
}
Having said that, your algorithm is not as efficient as using a built in algorithm. Try GroupBy
var duplicates = numbers.GroupBy(n => n)
.Where(group => group.Count() > 1);
foreach (var group in duplicates)
{
Console.WriteLine("{0} appears {1} times", group.Key, group.Count());
}
One way to get distinct numbers is
var uniqueNumbers = numbers.Distinct().ToArray()
and then iterate over uniqueNumbers like you have in your snippet with numbers.
You can add the number to a HashSet as you loop and then only print if not in hash set.
That allows you to do it in one pass.
The algorithm above is n^2 which should be avoided.
// deletes an integer if it appears double
#include <iostream.h>
#include <conio.h>
int main ()
{
int count=0;
int ar[10]={1,2,3,3,3,4,5,6,7,7};
for (int i=0; i<10; i++)
{
if (ar[i]==ar[i+1])
count++;
else
cout << ar[i];
}
getch();
return 0;
}
精彩评论