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

von Mexx (2370 Punkte)
- 17.07.2015 um 14:54 Uhr

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Häufigstes_Element_in_Array { class Program { static void Main(string[] args) { // Testarrays anlegen string[] teststrings = new string[] { "ab", "bb", "cc", "ab", "de", "aa", "bb", "ef", "xy", "aa", "ca", "ca", "ac", "aa", "yy", "gh", "gf", "bb", "ax", "za", }; int[] testzahlen = new int[] { 1, 2, 0, 1, 7, 5, 6, 6, 0, 7, 5, 9, 3, 7, 6, 1, 4, 9, 7, 4, 3, 2, 5, 6, 6, 8, 2, 7, 6, 1, 6 }; Testklasse[] test = new Testklasse[] { new Testklasse(1, 2), new Testklasse(3, 2), new Testklasse(2, 2), new Testklasse(1, 2), new Testklasse(1, 2), new Testklasse(2, 2), }; // Methode testen string str = (string)GetElement(teststrings); int zahl = (int)GetElement(Array.ConvertAll(testzahlen, new Converter<int, object>(IntegerToObject))); Testklasse t = (Testklasse)GetElement(test); } /// <summary> /// Gibt das erste gefundene Elemen der am häufigsten vorkommenden Elemente eines Arrays als Objekt zurück /// </summary> /// <param name="array">Das zu überprüfende Array (Arrays mit Zahlenwerten müssen explizit konvertiert werden)</param> /// <returns>Das am Häufigsten vorkommende Objekt (muss wieder in seinen ursprünglichen Datentyp umgewandelt werden)/returns> private static object GetElement(object[] array) { object obj = null; Hashtable ht = new Hashtable(); foreach (object o in array) if (ht.ContainsKey(o)) ht[o] = (int)ht[o] + 1; else ht.Add(o, 1); int maxAnzahl = ht.Values.Cast<int>().Max(); foreach (DictionaryEntry entry in ht) if ((int)entry.Value == maxAnzahl) { obj = entry.Key; break; } return obj; } private static object IntegerToObject(int i) { return (object)i; } } /// <summary> /// Testklasse /// </summary> class Testklasse { int a; int b; public Testklasse(int a, int b) { this.a = a; this.b = b; } } }
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1