Die Gauss'sche Glocke (Simulationen)
Verwenden Sie einen Zufallszahlengenerator um Würfelergebnisse (1-6) zu simulieren. Werfen Sie nun 5 Würfel und bilden die Augensumme.
Spielen Sie dieses Experiment 1000 Mal durch und geben Sie von jeder möglichen Augensumme (Minimum = 5, Maximum = 30) an, wie oft sie vorgekommen ist.
Klingelt's?
2 Kommentare
16 Lösung(en)
/**
* Feb. 2011
* @author Philipp Gressly (phi AT gressly DOT ch)
*/
public class GaussGlocke {
public static void main(String[] args) {
new GaussGlocke().top();
}
void top() {
int[] ergebnisse = new int[31]; // relevant: [5]..[30]
int experimentNr = 1;
while(experimentNr <= 1000000) {
int augenZahl = wirfFuenf();
ergebnisse[augenZahl] = ergebnisse[augenZahl] + 1;
experimentNr = experimentNr + 1;
}
ausgabe (ergebnisse);
}
void ausgabe(int[] ergebnisse) {
for(int sum = 5; sum <= 30; sum++) {
System.out.println(sum + " kommt " +
ergebnisse[sum] + " Mal vor.");
}
}
int wirfFuenf() {
return wurf() + wurf() + wurf() + wurf() + wurf();
}
int wurf() {
return (int) (Math.random() * 6) + 1;
}
} // end of class GaussGlocke
Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
# @autor Philipp Gressly Freimann
# 7. April 2011
#
# Aufgabe http://www.programmieraufgaben.ch / http://www.programmieren-lernen.ch
# Gauss'sche Glocke
def simulation(anzahl)
versuch = 1
while(versuch <= anzahl)
wirf()
versuch = versuch + 1
end
end
def wirf()
summe5 = wirfNMal(5)
$glocke[summe5] = $glocke[summe5].to_i + 1
end
def wirfNMal(anzahlWuerfe)
summe = 0
wurf = 1
while(wurf <= anzahlWuerfe)
augenZahlAktuellerWurf = 1 + rand(6)
summe = summe + augenZahlAktuellerWurf
wurf = wurf + 1
end
return summe
end
def ausgeben()
pos = 5
while(pos <= 30)
puts "Wurf #{pos} kommt #{$glocke[pos].to_i} Mal vor."
pos = pos + 1
end
end
################
##### MAIN #####
################
# Globale Variable als Zähler für jede Augensumme:
$glocke = Array.new
simulation(1000)
ausgeben()
##### END #####
Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)
import random
w =[0 for i in range (5)] # Eine Liste fuer die 5 Wuerfel wird erzeugt
v = [[i,0] for i in range (31)] # Eine Liste fuer die Augensumme-Verteilung wird erzeugt
for n in range (1000): # Das Spiel wird 1000 Mal wiederholt
s = 0 # Augensumme
for i in range (5):
w[i] = random.randint(1,6)
s = s + w[i]
v[s][1] = v[s][1] + 1
for n in range (5, 31):
print "Die Augensumme", v[n][0], "ist", v[n][1], "Mal vorgekommen"
Lösung von: Name nicht veröffentlicht
/*--- Programm-Parameter ---*/
DCL KO_RUNDEN BIN FIXED(31) VALUE(1000);
DCL KO_ANZWURF BIN FIXED(31) VALUE(5);
DCL KO_MIN BIN FIXED(31) VALUE(5);
DCL KO_MAX BIN FIXED(31) VALUE(30);
/*--- Interne Variablen ---*/
DCL TAB_COUNT(KO_MAX) BIN FIXED(31) INIT((30)0);
DCL IND_RUNDE BIN FIXED(31) INIT(0);
DCL IND_WURF BIN FIXED(31) INIT(0);
DCL IND_TAB_COUNT BIN FIXED(31) INIT(0);
DCL ZW_ZAHL BIN FIXED(31) INIT(0);
/*--- Programm ---*/
DO IND_RUNDE = 1 TO KO_RUNDEN;
ZW_ZAHL = 0;
DO IND_WURF = 1 TO KO_ANZWURF;
ZW_ZAHL += TRUNC((RANDOM()*6)+1);
END; /* IND_WURF = 1 TO KO_ANZWURF */
TAB_COUNT(ZW_ZAHL) += 1;
END; /* IND_RUNDE = 1 TO KO_RUNDEN */
/*--- Auswertung ---*/
DO IND_TAB_COUNT = KO_MIN TO KO_MAX;
PUT SKIP LIST(IND_TAB_COUNT !! ': ' !! TAB_COUNT(IND_TAB_COUNT));
END; /* IND_TAB_COUNT = KO_MIN TO KO_MAX */
Lösung von: Valentin Marolf (AXA)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static int verteilung[30 + 1 - 5];
#define V(summe) verteilung[(summe) - 5]
int main(void)
{
long summe;
int i, j;
srandom(time(NULL));
for (i = 0; i < 1000; i++) {
summe = 0;
for (j = 0; j < 5; j++)
summe += (((long) random()) % 6) + 1;
V(summe)++;
}
for (i = 5; i <= 30; i++)
printf("%d: %d\n", i, V(i));
return EXIT_SUCCESS;
}
Lösung von: Jonathan Neuschäfer (St.-Bernhard-Gymnasium, 47877 Willich)
class Program
{
static void Main(string[] args)
{
foreach (KeyValuePair<int, int> r in WürfelExperiment.experiment().OrderBy(i => i.Key))
Console.WriteLine("{0:00} => {1:000}", r.Key, r.Value);
Console.ReadLine();
}
private static int getAugenZahl()
{
Random r = new Random(DateTime.Now.Millisecond);
return r.Next(1, 6);
}
private static int[] getWuerfel(int count)
{
int[] res = new int[5];
for (int i = 0; i < count; ++i)
res[i] = getAugenZahl();
return res;
}
public static Dictionary<int, int> experiment()
{
Dictionary<int, int> res = new Dictionary<int, int>();
for (int i = 0; i < 1000; ++i)
{
int[] wuerfel = getWuerfel(5);
int tmp = wuerfel.Sum();
if (res.ContainsKey(tmp)) res[tmp]++;
else res.Add(tmp, 1);
}
return res;
}
}
Lösung von: Luca Welker (SBS Software GmbH)
<?php
$wurfsum = 0;
$countArr = array();
$roundSum = array();
$temp = '';
for ($i = 0; $i < 1000; $i++) {
for ($w = 0; $w < 5; $w++) {
$wurfErgebnis = mt_rand(1, 6);
$wurfsum += $wurfErgebnis;
}
$roundSum[] = $wurfsum;
$wurfsum = '';
}
$counter = '0';
foreach ($roundSum as $val) {
for ($i = 0; $i < count($roundSum); $i++) {
if ($roundSum[$i] == $val) {
$counter += 1;
}
}
$countArr[$val] = $counter;
$counter = 0;
}
foreach ($countArr as $key => $value) {
echo $key . " Zahl ";
echo $value . " Vorkommen " . "\n";
}
var_dump($roundSum);
?>
Lösung von: Lara Korner (HTL Innsbruck)
// Autor: Andy Großhennig
// Solution for task: Die Gauss'sche Glocke (Simulationen)
#include <iostream>
#include <Windows.h>
using namespace std;
// Function: Returns a Number between one and six
int toDice()
{
srand(GetTickCount());
return (rand() % 6) + 1;
}
// Function: Simulate
void bellofGauss()
{
int iEyes; //Amount of current eyes
int i_arrTotalEyes[26]; //Count-Array for amount of all eyes
// Loop: Set all array positions to zero
for(int iFirst = 0;iFirst < 26;iFirst++)
{
i_arrTotalEyes[iFirst] = 0;
}
// Loop: Continue 1000 time's
for(int iFirst = 0;iFirst < 1000;iFirst++)
{
iEyes = 0;
// Loop: to dye
for(short shSecond = 0;shSecond < 5;shSecond++)
{
iEyes += toDice();
Sleep(1);
}
i_arrTotalEyes[iEyes - 5]++; //Increments the counts
}
//Loop: Show the result
for(short shFirst = 5;shFirst <= 30;shFirst++)
{
printf("Gewuerfelte %ien: %i\n", shFirst, i_arrTotalEyes[shFirst - 5]);
}
}
int main()
{
bellofGauss();
printf("\n\n");
system("Pause");
return 0;
}
Lösung von: Andy Großhennig (Bundeswehr)
import random
d = {i:0 for i in range(5, 30+1)}
for i in range(1000):
s = sum([random.randint(1, 6) for j in range(5)])
d[s] += 1
for k in sorted(d.keys()):
print("{0:>2}: {1:>3}".format(k, d[k]))
Lösung von: Karl Welzel ()
# Python 3.4.2
from random import randint
# Dict mit Haeufigkeiten der Augensummen generieren
haeufigkeiten = dict.fromkeys(range(5, 31), 0)
# 1000 Wuerfe simulieren und jedesmal das dict haeufigkeiten aktualisieren
for i in range(1000):
augensumme = 0
for f in range(5):
augensumme += randint(1, 6)
print(augensumme)
haeufigkeiten[augensumme] = haeufigkeiten[augensumme] + 1
# Ausgabe der Verteilung
for i in range(5, 31):
print('Augensumme', i, 'gab es', haeufigkeiten[i], 'mal.')
Lösung von: Hilli Hilli ()
using System;
using System.Collections.Generic;
using System.Linq;
namespace Die_Gausssche_Glocke {
class Program {
static int getAugen(int würfelAnzahl = 5, int seitenAnzahl = 6) {
int intToReturn = 0;
seitenAnzahl++;
for (int i = 0; i < würfelAnzahl; i++)
intToReturn += Singleton.Random.Next(1, seitenAnzahl); //mit Singleton, zuverlässig
//intToReturn += new Random(DateTime.Now.Millisecond).Next(1, seitenAnzahl); //ohne Singleton, unzuverlässig
return intToReturn;
}
static void Main() {
Dictionary<int, int> Ergebnisse = new Dictionary<int, int>();
for (int i = 1, temp_augen; i < 1001; i++) {
temp_augen = getAugen();
if (Ergebnisse.ContainsKey(temp_augen))
Ergebnisse[temp_augen]++;
else
Ergebnisse.Add(temp_augen, 1);
}
foreach (KeyValuePair<int, int> Ergebnis in Ergebnisse.OrderBy(x => x.Key))
Console.WriteLine("{0,2} Augen: {1,3}x",Ergebnis.Key, Ergebnis.Value );
Console.ReadKey(true);
}
}
public class Singleton {
static Random random = null as Random;
public static Random Random {
get {
if (random == null)
random = new Random();
return random;
}
}
}
}
Lösung von: Marcel Kapma ()
<?php
//überschrift
echo 'Mit 5 Würfeln wurde 1000 mal gewürfelt<br>';
echo '<br>';
//inizialisierung
for($t = 0; $t <= 31; $t++){
$arrayergebnis[$t] = 0;
}
//würfeln + aufsumieren
for($i = 0; $i < 1000; $i++){
$wuerfel = mt_rand(5, 30);
$arrayergebnis[$wuerfel]++;
}
//ausgabe
for($h = 5; $h <= 30; $h++){
echo 'Die '. $h . ' wurde '. $arrayergebnis[$h]. 'x gewürfelt.<br>';
}
Lösung von: Julian Mueller (BSZ Würzburg)
var rolls = [],
x;
for (x = 0; x <= 30; x++) rolls[x] = "+";
// die würfelei
var roll = function() {
var sum = 0;
for (var x = 1; x <= 5; x++) sum += Math.floor(Math.random()* 6) + 1;
return sum;
}
// jede gewürfelte summe bekommt einen strich zur visualisierung
// (geht ja schließlich um die glocke)
for(x = 1; x <= 1000; x++) rolls[roll()] += "-";
// ausgabe
for(x = 1; x <= 26; x++)
document.write(
rolls[x+4] +
"(" + parseInt(x+4) + ": " +
parseInt(rolls[x+4].length-1) + ")<br>"
);
/* Screenshot einer ausgabe: ----------------------------------------\
| https://dl.dropboxusercontent.com/u/36859567/gauszscheGlocke.gif |
\-------------------------------------------------------------------*/
Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)
<?php
$ar = [];
for ($i=0; $i<1000; $i++)
{
$x = array(mt_rand(1,6), mt_rand(1,6), mt_rand(1,6), mt_rand(1,6), mt_rand(1,6));
$y = array_sum($x);
array_push($ar, $y);
}
$z = array_count_values($ar);
natsort($z);
foreach ($z as $key => $value)
{
echo "Summe: " . $key . ", Anzahl: " . $value . "<br>";
}
?>
Lösung von: Maik Scheiermann (Powercloud GmbH)
from random import randint
ListeAugensumme = [0] * 26
for i in range(1000):
augensumme = 0
for j in range(5):
augensumme += randint(1, 6)
ListeAugensumme[augensumme - 5] += 1
for i in range(5, 31):
print(i, ListeAugensumme[i - 5])
Lösung von: Peter Pan (Home Office)
// NET 6.x | C# 10.x | VS-2022
Enumerable.Range(1, 1000).Select(x => Enumerable.Range(1, 5)
.Select(x => new Random().Next(1, 7)).Sum()).GroupBy(x => x)
.Select(x => new { points = x.Key, count = x.Count() }).OrderBy(x => -x.points).ToList()
.ForEach(x => Console.WriteLine($"{x.points,4} Pkt x {x.count,4} | {new string('.', x.count)}"));
Lösung von: Jens Kelm (@JKooP)
Verifikation/Checksumme:
Die Summen 17 und 18 sollten am häufigsten (je etwas über 100 Mal) auftreten.
Aktionen
Neue Lösung hinzufügen
Bewertung
Durchschnittliche Bewertung:
Meta
Zeit: | 0.25 |
Schwierigkeit: | Leicht |
Webcode: | 7hvi-0axa |
Autor: | Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch) |
Kommentare (2)
Ich habe eine eigene Lösung zwecks Vergleich angefertigt.
Da diese Methode steht's eine neue Instaz der Klasse Random erstellt, wird der Seed (DateTime.Now.Millisecond) jedes mal von vorne durchlaufen. Jede Mittelklasse CPU schafft es ohne weiteres mehrere dieser Instanzen in der selben Millisekunde zu erstellen, womit immer wieder die selbe Zufallszahl generiert wird. Hier sollte ein Singleton, eine globale statische Instanz oder eine Instanz per Depency Injection verwendet werden, damit immer die selbe Instanz aufgerufen und keine neue erstellt wird. Ein schneller Test auf meinen System ergab dass die selbe Zahl ca. 15 mal hintereinander generiert wird.
Desweiteren reicht die Weite der zurückgegebenen Zufallswerte von einschließlich 1 bis einschließlich 5. Der Methode Next() muss (1, 7) übergeben werden. Der erste Parameter ist inklusive, der zweite Parameter exklusive.