John Davidson

sorting - A list of random float number from 0 to 1 using php?

0 comments
Message:


I want to create a function to print a list of 50 random floats from 0 to 1.


The function to print one random float is simply :


function random_from_0_to_1() 
{
return (float)rand() / (float)getrandmax();
}

But how do I get a list of 50 numbers in descending order?


I want to use usort() function, but I am not sure how to use it with a list of 50 random floats.



My Answer:
Here is an example of how you can use the `usort()` function to sort a list of 50 random floats in descending order:

php
function random_from_0_to_1()
{
return (float)rand() / (float)getrandmax();
}

$random_floats = array();

// Generate 50 random floats and store them in an array
for ($i = 0; $i < 50; $i++) {
$random_floats[] = random_from_0_to_1();
}

// Sort the array in descending order
usort($random_floats, function($a, $b) {
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
});

// Print the sorted array
foreach ($random_floats as $float) {
echo $float . "\n";
}


This code will generate 50 random floats between 0 and 1, store them in an array, and then use the `usort()` function to sort the array in descending order. Finally, it will print out the sorted array.

Rate this post

3 of 5 based on 3899 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us