C# :: Aufgabe #102 :: Lösung #9
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.
#9

von Exception (7090 Punkte)
- 21.07.2018 um 19:46 Uhr

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace haeufigstesElementInArray102 { class Program { static void Main(string[] args) { int[] blub = new int[100]; Dictionary<int, int> mostCommonElements = new Dictionary<int, int>(); fillArray(ref blub, blub.Length); getMostCommonElements(ref mostCommonElements, ref blub); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine("Zahl\t\tAnzahl"); Console.ResetColor(); foreach (var element in mostCommonElements.OrderByDescending(key => key.Value)) { Console.WriteLine("{0}\t=>\t{1}", element.Key, element.Value); } Console.WriteLine("-------------------------------------"); Console.WriteLine("Einzigartige Zahlen\t=>\t{0}", mostCommonElements.Count); Console.ReadKey(); } private static void getMostCommonElements(ref Dictionary<int, int> mostCommonElements, ref int[] blub) { int currentNumber = -1; for (int i = 0; i < blub.Length; i++) { currentNumber = blub[i]; if(!mostCommonElements.ContainsKey(currentNumber)) { mostCommonElements.Add(currentNumber, 0); } for (int j = 0; j < blub.Length; j++) { if(currentNumber == blub[j]) { mostCommonElements[currentNumber]++; } } } } private static void fillArray(ref int[] blub, int len) { Random r = new Random(); for (int index = 0; index < len; index++) { blub[index] = r.Next(1, 101); } } } }
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1