Häufigstes Element in Array (Feld) suchen (Felder)
Gegeben ist ein Array zum Beispiel mit Zahlen als Werten:
{2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14}
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.
0 Kommentare
21 Lösung(en)
- java
- python
- python
- python
- javascript
- javascript
- lisp
- groovy
- ruby
- csharp
- python
- csharp
- java
- c
- php
- abap
- javascript
- java
- csharp
- cpp
- cpp
package ch.programmieraufgaben.arrays;
import java.util.Arrays;
/**
* Gegeben ist ein Array zum Beispiel mit Zahlen als Werten:
* {2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14}
* 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.
*
* @version 0.1 (Jun 21, 2015)
* @author Philipp Gressly Freimann
* (philipp.gressly@santis.ch)
*/
public class FindeHaeufigstesInArray {
public static void main(String[] args) {
new FindeHaeufigstesInArray().top();
}
void top() {
int[] feld = { 2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14 };
int haeufigstes = haeufigstes(feld);
System.out.println("Das häufigstste Element ist " + haeufigstes);
}
int haeufigstes(int[] orig) {
Arrays.sort(orig);
// finde längste Sequenz
int found = orig[0];
int foundLen = findLen(orig, 0);
for(int i = 1; i < orig.length;) {
int actLen = findLen(orig, i);
if(actLen > foundLen) {
found = orig[i];
foundLen = actLen;
}
i = i + actLen;
}
return found;
}
int findLen(int[] alle, int startPos) {
int startElement = alle[startPos];
int len = 1;
for(int i = startPos + 1; i < alle.length; i++) {
if(alle[i] != startElement) {
return len;
}
len ++;
}
return len;
}
} // end of class FindeHaeufigstesInArray
Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)
from collections import Counter
Counter([2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14])
Lösung von: Py Thon ()
"""Finde das Häufigste Element in einer Liste/in einem Array
(Algorithmisch)."""
def zaehlen(*zahlen):
letztes = 0
aktuelles = 0
hauefigstes = 0
for i in zahlen:
aktuelles = zahlen.count(i)
if aktuelles > letztes:
letztes = aktuelles
hauefigstes = i
return hauefigstes
print zaehlen(2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14)
Lösung von: Robin Pal (Westfälische Hochschule Gelsenkirchen)
# -*- coding: utf-8 -*-
tup1 = (2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14)
bestesElement = 0
besteAnzahl = 0
for i in tup1:
if tup1.count(i) > besteAnzahl:
bestesElement = i
besteAnzahl = tup1.count(i)
print "\nHäufigstes Element ist die ", bestesElement, " mit ", besteAnzahl, " Treffern"
Lösung von: J. Reppe ()
var zahlenarr = new Array(2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14, 9);
var i = 0;
var o = 0;
var counter = 0;
var meisteZahl = 0;
var anzahl = 0;
while(i <= zahlenarr.length)
{
while(o <= zahlenarr.length)
{
if(zahlenarr[i] == zahlenarr[o])
{
counter++;
}
o++;
}
if(counter > anzahl)
{
anzahl = counter;
meisteZahl = zahlenarr[i];
}
i++
counter = 0;
o = 0;
}
document.write("Die Zahl " + meisteZahl + " kommt in deinem Array am häufigsten vor" );
Lösung von: Name nicht veröffentlicht
var a = [2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14],
major = [-1],
majorSum = 0,
sum = 0,
times = 0,
for(var i = 0; i<a.length; i++){
sum = 0;
for(var e in a){
if(a[e]==a[i]){
sum++;
if(sum > majorSum){
majorSum = sum;
major.splice(0, major.length);
major[0] = i;
}
else if(sum == majorSum){
major.push(i);
times++;
}
}
}
}
major.splice(major.length-times/2, times/2);
for(var el in major)
document.write(a[major[el]]+" is in the array: "+majorSum+" times<br/>");
Lösung von: MSM Programming ()
F# Lösung:
let list = seq [2; 17; 10; 9; 16; 3; 9; 16; 5; 1; 17; 14;]
let duplicates xs =
Seq.scan (fun xs x -> Set.add x xs) Set.empty xs
|> Seq.zip xs
|> Seq.choose (fun (x, xs) -> if Set.contains x xs then Some x else None)
|> Seq.last
printfn "%A" (duplicates list)
Lösung von: Vural Acar ()
//Gibt alle häufigsten aus
println([2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14].countBy { it }.groupBy { it.value }.max { it.key }.value.keySet())
//Gibt das erste Element der Liste aus
println([2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14].countBy { it }.groupBy { it.value }.max { it.key }.value.keySet()[0])
Lösung von: Max Jando (Hochschule Mannheim)
$num = [2,17,10,9,16,3,9,16,5,1,17,14]
def most_common (arr)
arr.group_by(&:itself).values.max_by(&:size).first
end
puts most_common $num
gets
Lösung von: Name nicht veröffentlicht
using System;
namespace Häufigstes_Element_in_Array__Feld__suchen
{
/*
* Autor: Hade Mohamed | HTL Bulme
* Contact: proxfreak@gmail.com
*/
/*
* Gegeben ist ein Array zum Beispiel mit Zahlen als Werten:
{2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14}
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.
*/
class Program
{
static int GetCount(int[] a, int n)
{
int count = 0;
for (int i = 0; i < a.Length; i++)
if (a[i] == n)
count++;
return count;
}
static void Main(string[] args)
{
int[] Zahlen = { 2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14 };
int top = Zahlen[0];
int count = GetCount(Zahlen, top);
for (int i = 0; i < Zahlen.Length; i++)
{
int count2 = GetCount(Zahlen, Zahlen[i]);
if (count < count2)
{
top = Zahlen[i];
count = count2;
}
}
Console.WriteLine("Die am meisten auftretende Zahl im Feld ist: " + top + ".\nAnzahl der Auftritte: " + count);
Console.ReadLine();
}
}
}
Lösung von: Name nicht veröffentlicht
from random import randint
liste= [2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14,]
bishergrößtezahl = 0
for element in liste:
if element > bishergrößtezahl:
bishergrößtezahl = element
print(bishergrößtezahl, liste.count(bishergrößtezahl))
Lösung von: Jasper -- (Gymnasium)
using System;
using System.Linq;
namespace Häufigstes_Element_in_Array
{
class Program
{
static void Main(string[] args)
{
int[] zahlen = { 2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14 };
IGrouping<int, int> ergebnis = zahlen.GroupBy(x => x).OrderByDescending(x => x.Count()).FirstOrDefault();
Console.WriteLine("Häufigstes Element: " + ergebnis.Key + " - (Anzahl: " + ergebnis.Count() + ")");
Console.ReadKey();
}
}
}
Lösung von: No Name (Nürnberg)
package javaapplication26;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
//Patrick Cipot
//Sebastian Kielbasa
public class JavaApplication26 {
public static void main(String[] args) {
int anz, von, bis, rand;
System.out.println("Wv Zahlen wollen Sie erzeugen?");
Scanner sc = new Scanner(System.in);
anz = sc.nextInt();
System.out.print("Von : ");
von = sc.nextInt();
System.out.print("Bis : ");
bis = sc.nextInt();
int[] array = new int[anz];
for (int i = 0; i < anz; i++) {
rand = (int) (Math.random() * bis) + 1;
if (rand < von) {
i--;
} else {
array[i] = rand;
}
}
pruefen(von, bis, array);
}
public static void pruefen(int von, int bis, int[] array) {
int[][] array2 = new int[bis - von + 1][2];
for (int d = 0; d < array2.length; d++) {
array2[d][0] = d + 1 + von;
}
for (int i = 0; i < array.length; i++) {
array2[array[i] - von][1]++;
}
Arrays.sort(array2, new Comparator<int[]>() {
@Override
public int compare(int[] i1, int[] i2) {
return ((Integer) i2[1]).compareTo((Integer) i1[1]);
}
});
System.out.printf("Die Zahl %d kommt %d x vor .\n", array2[0][0], array2[0][1]);
}
}
Lösung von: Sebastian Kielbasa (HTL-Donaustadt)
#include <stdio.h>
void mostOccurence(int a[], int length, int *number, int *count); // a = Feld; length = Länge vom Feld; *number = Addresse von der Variable indem die meistvorkommende Zahl gespeichert wird; *count = Addresse von der Variable in der die Anzahl vom Vorkommen der meistvorkommenden Zahl gespeichert wird
void ausgabe(int a[], int length, int _mostOccurence, int occurenceCount);
void main()
{
int A[12] = {2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14}; // 12 Mitglieder ^= length = 12
int mostOccurentNumber;
int occurenceCount;
mostOccurence(A, 12, &mostOccurentNumber, &occurenceCount);
ausgabe(A, 12, mostOccurentNumber, occurenceCount);
getchar();
}
void mostOccurence(int a[], int length, int *number, int *count)
{
int i, k, _count;
*number = a[0];
*count = 0;
for(i = 0; i < length; i++)
{
_count = 0;
for(k = 0; k < length; k++)
if(a[k] == a[i]) _count++;
if(_count > *count)
{
*count = _count;
*number = a[i];
}
}
}
void ausgabe(int a[], int length, int _mostOccurence, int occurenceCount)
{
int i;
printf("Feld: ");
for(i = 0; i < length; i++) printf("%d ", a[i]);
printf("\nDie Zahl %d ist mit %d Vorkommen, die meist vorkommende Zahl im Feld.\n\n", _mostOccurence, occurenceCount);
}
Lösung von: Name nicht veröffentlicht
<?php
$x = array(2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14);
$x = array_count_values($x);
natsort($x);
$z = max($x);
$maxs = array_keys($x, max($x));
foreach ($maxs as $key => $value)
{
echo "Die größte Zahl ist " . $value . ", die kommt " . $z . " mal vor.<br><br>";
}
?>
Lösung von: Maik Scheiermann (Powercloud GmbH)
REPORT zfreqlist.
" Frequenztabellenstruktur
TYPES: BEGIN OF tt_freqlist,
zahl TYPE i,
freq TYPE i,
END OF tt_freqlist.
" Einlesen der Eingabe
PARAMETERS: pa_1 TYPE string.
DATA: lt_zahlen TYPE STANDARD TABLE OF string,
ls_zahlen LIKE LINE OF lt_zahlen,
lt_freq TYPE STANDARD TABLE OF tt_freqlist,
ls_freq LIKE LINE OF lt_freq,
lv_helper TYPE i.
" Splitten der Eingabe in einzelne Zahlen
SPLIT pa_1 AT ',' INTO TABLE lt_zahlen.
" Frequenzliste wird mit den Zahlen befüllt.
LOOP AT lt_zahlen INTO ls_zahlen.
lv_helper = ls_zahlen.
ls_freq-zahl = lv_helper.
APPEND ls_freq TO lt_freq.
ENDLOOP.
" Frequenzliste wird mit der Frequenz befüllt.
LOOP AT lt_zahlen INTO ls_zahlen.
LOOP AT lt_freq INTO ls_freq.
IF ls_zahlen EQ ls_freq-zahl.
ADD 1 TO ls_freq-freq.
MODIFY lt_freq FROM ls_freq.
ENDIF.
ENDLOOP.
ENDLOOP.
" Frequenzliste wird nach Frequenz sortiert.
SORT lt_freq BY freq DESCENDING.
" Häufigster Eintrag wird eingelesen.
READ TABLE lt_freq INDEX 1 INTO ls_freq.
" Ausgabe.
WRITE: / ls_freq-zahl, 'kommt ' NO-GAP, ls_freq-freq NO-GAP, ' mal vor.'.
Lösung von: Alexander S. (msg systems)
function mostFrequentElement(arr) {
var max = 0,
element, temp;
arr.sort();
while (arr.length > 0) {
temp = arr.lastIndexOf(arr[0]) + 1 // anzahl der elemente von [0] aus
if (temp > max) { // häufigeres element vorhanden
max = temp;
element = arr[0];
}
arr.splice(0, temp); // elemente in der reihe entfernen
}
return element;
/* respektive mit rückgabe der anzahl: */
// return [element, max];
}
console.log(mostFrequentElement([2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14]));
Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)
import java.util.*;
public class Häufigstes {
public static void main(String args[]){
final List<Integer> values = Arrays.asList(2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14);
System.out.println(frequentElement(values));
}
static private int frequentElement(List<Integer> values) {
final Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int i : values)
frequencyMap.put(Collections.frequency(values, i), i);
return frequencyMap.get(Collections.max(frequencyMap.keySet()));
}
}
Lösung von: Hans Otto (privat)
var lst = Enumerable.Range(1, 100).Select(x => new Random().Next(1, 30));
Console.WriteLine(lst.GroupBy(x => x).Select(x => new { Zahl = x.Key, Anzahl = x.Count() }).OrderBy(x => -x.Anzahl).FirstOrDefault());
Lösung von: Jens Kelm (@JKooP)
// C++ 14 | VS-2022
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
std::map<int, int> get_grouped_vector(const std::vector<int>& v) {
std::map<int, int> m;
for (const auto& i : v)
if (m.count(i)) m[i]++;
else m.emplace(i, 1);
return m;
}
int get_frequency(const std::map<int, int> m) {
return std::max_element(m.begin(), m.end(), [](const auto& p1, const auto& p2) {return p1.second < p2.second; })->first;
}
int main() {
const std::vector<int> nums{2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14, 17};
const auto group{ get_grouped_vector(nums) };
const auto freq{ get_frequency(group) };
std::cout << std::to_string(freq) << std::endl;
}
Lösung von: Jens Kelm (@JKooP)
// C++ 20 | VS-2022
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <ranges>
template<typename _Ty> concept Numeric = std::is_arithmetic_v<_Ty>;
template<typename _Ty> requires Numeric<_Ty>
inline static constexpr auto get_grouped_vector(const std::vector<_Ty>& vec_) {
std::map<_Ty, size_t> map;
for (const auto& val : vec_)
if (map.count(val)) map[val]++;
else map.emplace(val, 1);
return map;
}
template<typename _Ty> requires Numeric<_Ty>
inline static constexpr auto get_most_freq_val(const std::map<_Ty, size_t> map_) {
return std::ranges::max_element(map_, std::less())->first;
}
int main() {
const std::vector<int> nums{ 2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14, 17 };
const auto group{ get_grouped_vector(nums) };
const auto freq{ get_most_freq_val(group) };
std::cout << "most frequently value: " << std::to_string(freq) << std::endl;
}
Lösung von: Jens Kelm (@JKooP)
Verifikation/Checksumme:
Im gegebenem Array kommen die Zahlen 9, 16 und 17 je zwei mal vor.
Aktionen
Neue Lösung hinzufügen
Bewertung
Durchschnittliche Bewertung:
Meta
Zeit: | 1 |
Schwierigkeit: | Mittel |
Webcode: | qurd-eugv |
Autor: | Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch) |