0
How to display the integer that appears the most in an array? Display as”the number x appears y times”...
5 odpowiedzi
+ 10
● sort the array in ascending order
● run a loop through that array counting distinct elements
● make an array of all those distinct elements using 2nd ●(we get number of distinct elements) & running through original array [we made array2]
● make array3 of same length of number of distinct elements(correspoding to elemnts of array2)
●make a loop for running in array of distinct elements(array3) & inside it a loop on original array counting number of times a particular elements comes & putting it in array3
//now U have distinct elemnts in array2 & correspoding number of times they repeated in array3
//now using that array 3 , U can find max number using Array.sort() & taking last element then matching that number in original non-sorted array & finding element repeated most time .
NOTE : there is a direct way we can print every element with number of times they repeated only by using loops(& not creating any more array) but will not be able to store that information . [U can try it by yourself]
+ 1
thanks
0
ok
0
This probably isn't the best way to do it, but in case anyone wants to see a code example for it:
int[] array = { 1, 2, 1, 3, 1, 4, 5, 6, 7, 8, 6, 1, 7, 8, 9, 0 };
//sorting by lowest to highest
Array.Sort(array, (y, x) => y.CompareTo(x));
Dictionary<int, int> dict = new Dictionary<int, int>();
for(int i = 0; i < array.Length - 1; i++)
{
//if the neighbour is equal to the current
if (array[i] == array[i + 1])
{
//if it isn't present in the dictionary
if(!dict.Keys.Contains(array[i]))
{
//add it and increment to the value
dict.Add(array[i], 1);
dict[array[i]]++;
}
else
{
//otherwise just increment
dict[array[i]]++;
}
}
}
//finally, print the results to console
foreach (KeyValuePair<int, int> kvp in dict)
Console.WriteLine(quot;num: {kvp.Key}\ncount: {kvp.Value}");