How do I find duplicates in an array and display how many times they occurred?
Since you can't use LINQ, you can do this with collections and loops instead:
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)
{
// When the key is not found, "count" will be initialized to 0
dict.TryGetValue(value, out int count);
dict[value] = count + 1;
}
foreach(var pair in dict)
Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
Console.ReadKey();
}
How do I find duplicates in an array and display how many times they occurred python?
This is only a correction of your code. It is a possible solution but like in the other answers already shown, it is a lot easier to accomplish with collections.Counter
.
(1) You need to make an if / else
statement. You set the value of your dict to 1 in every loop, regardless if it is already existent or not. (if you have a value in your list which count is bigger than 2, this will lead to wrong results)
(2) wrong syntax here: =+
needs to be +=
.
(3) don't name a variable same as build-in names. dict
should not be a variable name. better: dic
or my_dict
etc.
a = [1, 2, 2, 3, 4]
dic = {}
for i in a:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
print(dic)
{1: 1, 2: 2, 3: 1, 4: 1}
You only want to get the key of the value which has the biggest frequency in your list. Therefore you need to use max
with a key (you don't want to get the maximum of keys, you want to get the maximum of its values and return the key of that maximum.
result = max(dic.items(), key=lambda tup: tup[1])
# this would return in this case a tuple with (key,value): (2, 2). you only want to get the key:
print(result[0])
# 2
How do I count occurrence of duplicate items in array
array_count_values
, enjoy :-)
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);
Result:
No. of NON Duplicate Items: 7
Array
(
[12] => 1
[43] => 6
[66] => 1
[21] => 2
[56] => 1
[78] => 2
[100] => 1
)
Find duplicate element occur more than two times from an array in java
You want to iterate through your array only one time. If all you want is duplicates, you can do this simply by keeping track of any value you have seen before using an ArrayList
:
int[] data = {5, 6, 1, 6, 9, 5, 2, 1, 5};
System.out.println(Arrays.toString(data));
ArrayList<Integer> seenBeforeList = new ArrayList<>();
for(int index = 0; index < data.length; index++){
int value = data[index];
if(seenBeforeList.contains(value)){
System.out.println("Duplicate Element : " + value);
System.out.println("Index of that duplicate element : " + index);
} else {
seenBeforeList.add(value);
}
}
Output:
[5, 6, 1, 6, 9, 5, 2, 1, 5]
Duplicate Element : 6
Index of that duplicate element : 3
Duplicate Element : 5
Index of that duplicate element : 5
Duplicate Element : 1
Index of that duplicate element : 7
Duplicate Element : 5
Index of that duplicate element : 8
If you want to group by value, then it would make more sense to use a HashMap
, storing the value as the key, and the indexes as the value. Then simply iterate through the HashMap
.
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
You could sort the array and then run through it and then see if the next (or previous) index is the same as the current. Assuming your sort algorithm is good, this should be less than O(n2):
const findDuplicates = (arr) => { let sorted_arr = arr.slice().sort(); // You can define the comparing function here. // JS by default uses a crappy string compare. // (we use slice to clone the array so the // original array won't be modified) let results = []; for (let i = 0; i < sorted_arr.length - 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } return results;}
let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7];console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);
How to find repetitions/duplicates in the array within 10 elements apart
This code finds the first item with the higher number of occurrences inside the "numbers" array (within n = 10 elements):
int n = 10;
int[] numbers = new int[] {1,5,5,4,5,6,7,8,9,10,11,12,13,14,1,16,17,5};
int mostDuplicatedNumber = 0, numberOfMaxOccurrences = 0;
for(int count = 0; count < numbers.Length - n; count++)
{
var groupOfNumbers = numbers.Skip(count).Take(n).GroupBy(i => i).OrderByDescending(i => i.Count());
if(numberOfMaxOccurrences < groupOfNumbers.First().Count())
{
numberOfMaxOccurrences = groupOfNumbers.First().Count();
mostDuplicatedNumber = groupOfNumbers.First().Key;
}
}
Console.WriteLine("Most duplicated number is " + mostDuplicatedNumber + " with " + numberOfMaxOccurrences + " occurrences");
Printing only the duplicates from an int array and how many times they occur
You can it either with HashMap
or with Simple sorting
, as your per comments simple method is as below
int[] array = new int[]{12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87};
int counter = 0,
temp = 0;//variable that holds the temporary value of each element
Arrays.sort(array);
temp=array[0];
int count=1;
for(int i=1;i<array.length;i++)
{
//System.out.println(array[i]);
if(temp==array[i])
{
count++;
}
else
{
if(count==1)
{
count=1;
}
else{
System.out.println(array[i-1]+" "+count);
count=1;
}
temp=array[i];
}
}
Related Topics
Entity Framework Creates a Plural Table Name, But the View Expects a Singular Table Name
Efficient Way to Round Double Precision Numbers to a Lower Precision Given in Number of Bits
How to Get a List of Installed Updates and Hotfixes
How to Find the Parent Directory in C#
The Remote Server Returned an Unexpected Response: (413) Request Entity Too Large
How to Format 07/03/2012 to March 7Th,2012 in C#
Passing Parameters to Xslt Stylesheet via .Net
Global Setting for Asnotracking()
Convert Object to JSON String in C#
Getting Relative Virtual Path from Physical Path
Is an Int a 64-Bit Integer in 64-Bit C#
Add Parameter to Button Click Event
Newtonsoft JSON Deserialize Dictionary as Key/Value List from Datacontractjsonserializer