C# :: Aufgabe #102 :: Lösung #3
10 Lösungen
#102
Das Häufigste Element in einem Array
Anfänger - C#
von klhlubek19
- 16.07.2015 um 13:46 Uhr
Schreiben Sie ein Programm, das aus einem Array das häufigste Element findet. Sollte es mehrere gleicher Anzahl finden, so darf irgend ein Element dieser Häufigsten ausgegeben werden.
#3
von eulerscheZhl (5230 Punkte)
- 17.07.2015 um 15:54 Uhr
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace trainYourProgrammer
{
class MainClass
{
static void Main(string[] args)
{
int[] testArray = {1,2,3,4,1,2,3,4,5,2,3};
Console.WriteLine(String.Join(", ", FindMostFrequent(testArray)));
}
static T[] FindMostFrequent<T>(T[] array) where T: IComparable<T> {
//zähle, wie oft welcher Wert vorkommt
Dictionary<T,int> dict = new Dictionary<T, int> ();
foreach (T t in array) {
if (dict.ContainsKey (t))
dict [t]++;
else
dict.Add (t, 1);
}
//finde die Werte mit den meisten vorkommen
List<T> result = new List<T> ();
int maxCount = 0;
foreach (KeyValuePair<T,int> pair in dict) {
if (maxCount < pair.Value) {
result.Clear ();
maxCount = pair.Value;
}
if (maxCount == pair.Value)
result.Add (pair.Key);
}
result.Sort ();
return result.ToArray ();
}
}
}Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1
