Jump to content
JohnDoe

Ajutor functie PHP care sa genereze numere random

Recommended Posts

Am un exercitiu de facut, trebuie un algoritm (in functia big_dice() ) care sa foloseasca functia dice() si sa returneze numere random de la 1-100, ma puteti ajuta?

Codul este asta


<?php
/*
* Without using the rand() function, can you make a big_dice() function
* which returns a random int between 1-100, with even distribution
*
* You can and must use the dice() function within the big_dice() function
*
* Some simple testing code is included at the bottom to ensure
* even distribution and to calculate run-time.
*
* DELIVERABLES:
*
* -- All code, PHP files, etc., necessary to run your solution
* -- A Google Docs graph of the distribution of your results from the
* test function below

/**
* This is your only input function (use instead of rand())
* @ return int
*/
function dice() {
return rand(1, 6);
}

/**
* Here's the test -- create a random number between 1 and 100
* @ return int $result number between 1 and 100
*/
function big_dice() {
/*

figure out how to use the dice() function (as much as you like)
and just about anything else to generate a
random number between 1 and 100, with even distribution

but you can not use the rand() function or it's variants...
you can only use (and must use) the dice() function to generate it.

dice();

*/
return $result;
}


/**
* And here's the test of the big_dice() function
* echo's to page
* @ return null
*/
function test_big_dice($test_limit = 100000) {
$big_dice_rolls = array();
$start = microtime(true);
for ($i=0; $i<$test_limit; $i++) {
$big_dice_rolls[] = big_dice();
}
$stop = microtime(true);
$duration = round((($stop - $start)), 4);
$breakdown = array_count_values($big_dice_rolls);
arsort($breakdown); // anomolies would be at the top or bottom
echo "Tested {$test_limit} rolls in ~{$duration} sec<br/>";
echo "Ended up with ".count($breakdown)." total outputs<br/>";
foreach ( $breakdown as $int => $occurances ) {
$pecentage = round($occurances / $test_limit * 100, 2);
echo "{$int} => [{$pecentage}%] {$occurances}<br/>";
}
}

# might as well test this thing!
test_big_dice();

?>

Edited by JohnDoe
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...