The problem is that you're only resetting the count
when there's a match and the count
is greater than arr.Length/k
. You need to reset it at the end of the inner for
loop or better yet define it just before the inner for
loop since it isn't needed outside of that loop. Also I'm guessing you'll want to break from that loop as soon as the count
meets your condition or you'll keep writing out the same thing.
int[] arr = { 3, 1, 2, 2, 1, 2, 3, 3 };
int k = 4;
for(int i = 0; i < arr.Length; i++)
{
int count = 1;
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i] == arr[j])
{
count++;
if (count > (arr.Length / k))
{
Console.WriteLine(arr[i] + " " + i );
break;
}
}
}
}
However this will still produce results for duplicate values at other locations. For instance the array {3, 1, 2, 2, 1, 2, 3, 3, 3, 3, 3, 3} with k equal to 4 produces 3,0; 3,6; 3,7; and 3,8. Assuming you only want 3,0 then a better solution would be.
int[] arr = { 3, 1, 2, 2, 1, 2, 3, 3 };
int k = 4;
var results = arr.Select((x,i) => new {Value = x, Index = i})
.GroupBy(x => x.Value)
.Where(grp => grp.Count() > arr.Length / k)
.Select(grp => grp.First());
foreach(var r in results)
{
Console.WriteLine($"{r.Value} {r.Index}");
}
Or if you prefer to stick with for
loops instead of Linq then all you need is a HashSet<int>
to keep track of the values you've already seen.
int[] arr = { 3, 1, 2, 2, 1, 2, 3, 3 };
int k = 4;
HashSet<int> seen = new HashSet<int>();
for(int i = 0; i < arr.Length; i++)
{
if(!seen.Add(arr[i]))
{
continue;
}
int count = 1;
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i] == arr[j])
{
count++;
if (count > (arr.Length / k))
{
Console.WriteLine(arr[i] + " " + i );
break;
}
}
}
}
Note that Add
returns false when the value is already in the hash set.