C# :: Aufgabe #102
10 Lösungen

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.
Lösungen:

using System; using System.Collections.Generic; using System.Linq; namespace Most_in_Array { class Program { static void Main() { Random random = new Random(); int[] array = new int[15]; for(int i = 0; i < array.Length; i++) array[i] = random.Next(4); Dictionary<int, int> counter; counter = array.Distinct().ToDictionary(x => x, x => 0); foreach(int value in array) { counter[value]++; Console.Write("{0} ", value); } Console.WriteLine("\n{0}", counter.First(x => x.Value == counter.Values.Max()).Key); Console.ReadKey(true); } } }

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; } } }

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 (); } } }

using System; namespace Häufigstes_Element_im_Array { class Program { static void Main(string[] args) { //Einlesen der Größe des Arrays int anzahlElemente; Console.WriteLine("Bitte die Anzahl der Elemente des Arrays angeben: "); while (!int.TryParse(Console.ReadLine(), out anzahlElemente)) Console.WriteLine("Bitte eine Ganzzahl eingeben!"); //Randomarray erstellen var random = new Random(); var stringChars = new char[anzahlElemente]; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } //Feststellung Häufigkeit string[,] häufigkeitArray = new string[anzahlElemente, 2]; for (int i = 0; i < anzahlElemente; i++) { häufigkeitArray[i, 0] = Convert.ToString(stringChars[i]); häufigkeitArray[i, 1] = "1"; } for (int i = 0; i < anzahlElemente - 1; i++) { for (int j = 0; j < anzahlElemente - 1; j++) { if (häufigkeitArray[i, 0].Equals(häufigkeitArray[j + 1, 0])) { häufigkeitArray[i, 1] += "1"; } } } //Feststellung häufigstes Element string häufigstesElement = ""; int anzahlHäufigstesElement = 0; for (int i = 0; i < häufigkeitArray.GetLength(0) - 1; i++) { if (häufigkeitArray[i, 1].Length > anzahlHäufigstesElement) { anzahlHäufigstesElement = häufigkeitArray[i, 1].Length; häufigstesElement = häufigkeitArray[i, 0]; } } //Ausgabe Console.WriteLine("Die Anzahl der generierten Elemente beträgt: " + anzahlElemente + "."); Console.WriteLine("Das am häufigsten vorkommende Element des Arrays ist: " + häufigstesElement + "."); Console.WriteLine("Dieses Element kommt " + anzahlHäufigstesElement + " mal vor."); Console.ReadLine(); } } }

public void Haufigkeit(int[] alleZahlen) { int[] z = new int[11]; int buff = 0; foreach (int zahl in alleZahlen) { if (zahl != 0) { z[zahl - 2] += +1; } foreach (int i in z) { if (i > buff) { buff = i; } } } }

public void Haufigkeit(int[] alleZahlen) { int[] z = new int[100]; int buff = 0; foreach (int zahl in alleZahlen) { if (zahl != 0) { z[zahl - 2] += +1; } foreach (int i in z) { if (i > buff) { buff = i; } } } }

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Markup; namespace TheMost { class Program { static void Main(string[] args) { var values = new[] {"x", "a", "b", "c", "a", "a", "e", "b"}; var values2 = new[] { 1,2,3,4,555,666,777,888,666,2,2,2,2,1,4 }; var x = values.GroupBy(i => i).OrderByDescending(i => i.Count()).First(); var y = values2.GroupBy(i => i).OrderByDescending(i => i.Count()).First(); Console.WriteLine($"Item {x.Key} : {x.Count()} elements"); Console.WriteLine($"Item {y.Key} : {y.Count()} elements"); Console.ReadKey(); } } }

class Program { static void Main(string[] args) { //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. Random zahlrandom = new Random(); Console.Write("Geben Sie die Elementanzahl von Array ein "); string nString = Console.ReadLine(); int n; if (!int.TryParse(nString, out n) && n <= 0) { Console.WriteLine("Error ! die Anzahl muss eine ganze positive Zahl sein"); } else { int[] zahlArray = new int[n]; for (int i = 0; i < zahlArray.Length; i++) { zahlArray[i] = zahlrandom.Next(5); Console.Write(zahlArray[i] + " "); } Console.WriteLine(); int haufigsteZahl = haufigeZa(zahlArray, n); Console.WriteLine("Die häufigste Element von vorgegeben Array ist: " + haufigsteZahl); Console.ReadKey(); } } public static int haufigeZa( int[] array, int n) { int haufigsteZahl = 0; int max = 0 ; int[] wiederholungsAnzahl = new int[n]; bool[] test = new bool[n]; for (int i = 0; i < array.Length; i++) { if (test[i] == false) { for (int j = i + 1; j < array.Length; j++) { if (array[j] == array[i]) { wiederholungsAnzahl[i] += 1; test[j] = true; } } if (max < wiederholungsAnzahl[i]) { max = wiederholungsAnzahl[i]; haufigsteZahl = array[i]; } } } return haufigsteZahl ; } }

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); } } } }
NET 5.x; C# 9.x
C#-Code

using System; using System.Linq; var numbers = new int[] { 1, 3, 7, 1, 7, 5, 4, 6, 1, 7, 5, 9, 6, 7, 6, 1, 0, 9, 7, 4, 3, 0, 5, 6, 6, 8, 2, 7, 6, 1, 6 }; Console.WriteLine(MaxFreqValue(numbers)); static string MaxFreqValue(int[] arr) => arr.GroupBy(x => x).Select(x => new { value = x.Key, count = x.Count() }).OrderBy(x => -x.count).FirstOrDefault().ToString();