How do i compute frequency of the numbers in the range,let's say 10-19,using rand number generator array with 50 int?
I have this code so far:

       $arr = array_fill(0, 50, NULL);

for ($i = 0; $i < 50; $i ++) {
  $arr[$i] = rand(10, 19);

but not sure if rand() assigned correctly .Thanks for any solution.

1 Year
Discussion Span
Last Post by diafol

Hmm... The write to file and read it back is using too many resources and is not optimal.

I am not clear about your question. Do you mean you want to...

1) create a random generated number between a and b (inclusive) for an array size of 50
2) count frequency of each number between a and b in the array
2.1) AFTER the array is generated, OR
2.2) DURING the array is generated
3) when counting, you CAN or CANNOT use other built-in function

By the way, from PHP documentation stated, mt_rand($min, $max) gives a better result than rand($min, $max). Just for your information.


Taywin,tahnks for the idea.Yes you outlined the steps as i needed.

Edited by LibraryCode


Here's a quickie I knocked up. I got interested in why array_multisort wouldn't work with number-based keys, so got a bit carried away:

function generateFD($min,$max,$total,$sort='number',$order='ASC')
    $r = [];
        $r[] = mt_rand($min,$max);
    $counts = array_count_values($r);

    if(strtoupper($sort) == 'NUMBER')
        if(strtoupper($order) == 'ASC')
        return $counts;

    //Unfortunately simple asort won't sort the numbers after the frequencies
    //and array_multisort on numeric keys don't work
    //So this is a workaround
    $tmp = [];
    $keys = array_keys($counts);
    $vals = array_values($counts);
    foreach($counts as $k=>$v)
        $tmp[] = [$k,$v];
    if(strtoupper($order) == 'ASC')
        //FREQ (Lowest frequency first)
        array_multisort($vals, SORT_ASC, $keys, SORT_ASC, $tmp);
    }else {
        //FREQ (Highest frequency first)
        array_multisort($vals, SORT_DESC, $keys, SORT_ASC, $tmp);
    $counts = [];
    foreach($tmp as $v)
        $counts[$v[0]] = $v[1];
    return $counts;

$freqASC = generateFD(19,30,50,'freq');
$freqDESC = generateFD(19,30,50,'freq','DESC');
$numberASC = generateFD(19,30,50);
$numberDESC = generateFD(19,30,50,'number','DESC');

    table{border-collapse: collapse;}
    tr th, tr td{border: 1px solid black;}

        <th>Sort by Frequency Order by ASC</th>
        <th>Sort by Frequency Order by DESC</th>
        <th>Sort by Number Order by ASC</th>
        <th>Sort by Number Order by DESC</th>
        <td><pre><?php print_r($freqASC);?></pre></td>
        <td><pre><?php print_r($freqDESC);?></pre></td>
        <td><pre><?php print_r($numberASC);?></pre></td>
        <td><pre><?php print_r($numberDESC);?></pre></td>

Edited by diafol

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.