PMG2022/Felder und Zufallszahlen

Aus ProgrammingWiki

Wiki-Quelltext dieser Seite.

<language>Javascript</language>
== Zufallszahlen ==

Mit den nachfolgenden Funktionen lassen sich beliebige Zufallszahlen ereugen:

 Math.random() ... erzeugt eine (rationale) Zufallszahl $z$ im Intervall $0 \le z < 1$
 Math.floor(z) ... rundet die Zahl $z$ auf die nächstniedrigere ganze Zahl ab

Experimentiere mit diesen Funktionen, so dass große ''ganze'' Zufallszahlen generiert werden.

<run id="60dcb992c63d5">
Math.floor(Math.random() * 10);
</run>

Nun wird das Werfen eines Würfels simuliert.

<code id="60dcb992c6332">
function wuerfelzahl() {
 var w = Math.floor(Math.random() * 6 + 1);
 return w;
}
</code>

<run id="60dcba5eaaba1">
wuerfelzahl();
</run>

Hier wird ganz oft gewürfelt. <br>
Was passiert genau?

<code id="60dcbb8649ec8">
function wuerfe() {
 var w1 = 0, w2 = 0, z = 0;
 do {
  w2 = w1;
  w1 = wuerfelzahl();
  z++;
 }
 while (w1 != 6 || w2 != 6);
 return z;
}

function wuerfeln(anz) {
 var z = 0, mw = 0;
 for (var i = 1; i <= anz; i++)
  z = z + wuerfe();
 mw = z / anz;
 return mw;
}
</code>

<run id="60dcbb8649f58">
wuerfeln(10000);
</run>


== Zufallszahlen und Felder ==

Hier wird eine Anzahl Zufallszahlen ZZ aus einem Intervall "von" "bis" erzeugt.

<code id="60af9dd9355f3">
function erzeuge_Anzahl_ZZ(von, bis, anz) {
 var feld = new Array();
 for (var i = 0; i < anz; i++)
  feld[i] = Math.floor(Math.random() * (bis - von + 1) + von); 
 return feld;
}
</code>

<run id="60af9dd9356ea">
erzeuge_Anzahl_ZZ(10,50,10);
</run>


== Würfeln mit einem Würfel ==

Zunächst sei das Würfeln ohne Felder implementiert:

<code id="60dcbfe329ac7">
var AZ1 = 0, AZ2 = 0, AZ3 = 0, AZ4 = 0, AZ5 = 0, AZ6 = 0;

function wuerfelexp(anzahl) {
 for (var i = 1; i <= anzahl; i++) {
  var zufall = Math.floor(Math.random() * 6 + 1);
  if (zufall == 1) {AZ1++};
  if (zufall == 2) {AZ2++}; 
  if (zufall == 3) {AZ3++};
  if (zufall == 4) {AZ4++}; 
  if (zufall == 5) {AZ5++};
  if (zufall == 6) {AZ6++};
 }
 console.log("Zahl 1: " + AZ1);
 console.log("Zahl 2: " + AZ2);
 console.log("Zahl 3: " + AZ3);
 console.log("Zahl 4: " + AZ4);
 console.log("Zahl 5: " + AZ5);
 console.log("Zahl 6: " + AZ6);
}

</code>

<run id="60dcbfe329b49">
wuerfelexp(1000);

</run>


Nun sollen die Würfelwerte in einem Feld gespeichert werden:

<code id="60dcc6ae5a577">
function wuerfel2(anzahl) {
 var ZaehlFeld = new Array(0, 0, 0, 0, 0, 0);
 for (var i = 1; i <= anzahl; i++) {
  var zufall = Math.floor(Math.random() * 6 + 1);
  ZaehlFeld[zufall - 1]++;
 }
 return ZaehlFeld;
}

function wuerfelAusgabe2(ZaehlFeld) {
 for (var i = 0; i < ZaehlFeld.length; i++)
  console.log("Augenzahl " + (i + 1) + ": " + ZaehlFeld[i]);
}
</code>

<run id="60dcc6ae5a621">
var newZaehlFeld = wuerfel2(1000);
wuerfelAusgabe2(newZaehlFeld);
</run>