I'm working on a code that prints out duplicated integers from an array with the number of their occurrence. I'm not allowed to use LINQ, just a simple code. I think I'm so close but confused about how to get a correct output:
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(); } } }
To count the duplicates in an array:Copied! const arr = ['one', 'two', 'one', 'one', 'two', 'three']; const count = {}; arr. forEach(element => { count[element] = (count[element] || 0) + 1; }); // 👇️ {one: 3, two: 2, three: 1} console.
Method 1 (Basic)Use two loops. In the outer loop, pick elements one by one and count the number of occurrences of the picked element in the inner loop. This method doesn't use the other useful data provided in questions like range of numbers is between 1 to n and there are only two repeating elements.
For finding duplicates, Create a new List using original Arrays. Iterate through new List and remove elements by comparing elements in unique Arrays. Elements remaining in the new List will contain only duplicates.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With