22. April 2012
The syntax of JavaScript and PHP is very similar. How similar is shown by the following function that I wrote to generate a random password:
PHP code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php function randomPassword($length){ $password = ""; for($i=0; $i<$length; $i++){ $func = rand(0,2); if($func == 0) $password = $password.chr(rand(48,57)); else if($func == 1) $password = $password.chr(rand(65,90)); else if($func == 2) $password = $password.chr(rand(97,122)); } return $password; } $randomPassword = randomPassword(20); echo($randomPassword); ?> |
JavaScript code:
<script type="text/javascript" line="1"> function rand(min,max){ if (arguments.length === 0){ min = 0; max = 32767; } return Math.floor(Math.random() * (max - min + 1)) + min; } String.prototype.chr = function(code){ return String.fromCharCode(code); } function randomPassword($length){ $password = ""; for($i=0; $i<$length; $i++){ $func = rand(0,2); if($func == 0) $password += $password.chr(rand(48,57)); else if($func == 1) $password += $password.chr(rand(65,90)); else if($func == 2) $password += $password.chr(rand(97,122)); } return $password; } $randomPassword = randomPassword(20); document.write($randomPassword); </script>
20. April 2012
In PHP the rand() function returns a random number between a given minimum and maximum (by default 0 and 32767). The whole looks like this:
<?php $randomNumber = rand(1,100); // random number between 1 and 100 echo $randomNumber; ?>
The same function can be rebuild with JavaScript:
<script type="text/javascript"> function rand(min,max){ if (arguments.length === 0){ min = 0; max = 32767; } return Math.floor(Math.random() * (max - min + 1)) + min; } var randomNumber = rand(1,100); // random number between 1 and 100 document.write(randomNumber); </script>
14. März 2010
Um Zufallszahlen in Java zu erstellen, kann man die Bibliothek java.util.Random verwenden. Die Zufalls-Klasse von Java ist sehr vielseitig und bietet unter anderem die Möglichkeit, Zufallszahlen in einem bestimmten Bereich zu definieren. An dieser Stelle folgt ein kleiner Beispiel-Code, welcher 20 Zufallszahlen im Bereich von 0 bis 72 ausgibt:
1 2 3 4 5 6 7 8 9 10 | public void erstelleZufallsZahl() { Random zufallsgenerator = new Random(); for(int i=0; i<20; i++) { int zahl = zufallsgenerator.nextInt(72); System.out.println(zahl); } } |
Etwas ausführlicher:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.Random; public class JavaApplication1 { public static void main(String[] args) { erstelleZufallsZahl(); } public static void erstelleZufallsZahl() { Random zufallsgenerator = new Random(); for (int i = 0; i < 20; i++) { int zahl = zufallsgenerator.nextInt(72); System.out.println(zahl); } } } |

0