如何创建回答以下内容的函数:
function randomDigits($numDigits) {
$arrayRange = 1000;
if ($numDigits <= 0) {
return '';
} else{
for($i=0; $i<$arrayRange; $i++){
echo mt_rand(0, 50) ." ";
}
}
}
$maxq = 100;
for ($i = 1; $i <= $maxq; $i++) {
echo $i . "<br>\n";
randomDigits($i) . "<br>\n----<br>\n";
}
答案 0 :(得分:2)
如果将所有生成的数字存储到数组中,则可以使用array_count_values
这将计算数组中多个键值的出现次数(例如,如果有12个出现的数字7)并将结果返回到数组中。这仅适用于字符串和整数值。
<?php
$array = array( 'a', 'a', 'a', 'a', 'b', 'b', 'c' );
print_r(array_count_values($array));
?>
以上结果:
Array
(
[a] => 4
[b] => 2
[c] => 1
)
从那里,你应该能够轻松地完成你想要的所有方法和输出 这是与现有代码的基本集成......
$maxq = 100;
$returned_array = array();
for ($i = 1; $i <= $maxq; $i++)
{
$returned_array = randomDigits($i); // return the generated array
// merge 'add' the two arrays, like saying i = i +2 or
// merged_array = merged_array + array
array_merge($returned_array, $returned_array);
// here you now have one array of 1000 random values
// print_r($returned_array);
// lets do some math
print_r(array_count_values($returned_array));
// this will show how many values were duplicates...
// e.g
// Array (
// [43] => 25 the number 43 was generated 25 times
// [25] => 22 the number 25 was generated 22 times
// [1] => 28 ect...
// you can loop through this array here and see which value was generated several times,
// format the results nicely, and do all sorts of maths on it as you wish
}
function randomDigits($numDigits)
{
$arrayRange = 1000;
$generated_array = array(); // here is an actual array that will store the generated numbers
if ($numDigits <= 0)
{
return null;
}
else
{
for($i = 0; $i < $arrayRange; $i++)
{
$random = mt_rand(0, 50);
array_push($generated_array, $random); // add the random value to the array
}
// here you have your array of generated numbers
return $generated_array;
}
}
答案 1 :(得分:1)
此处示例 - http://codepad.org/9Dv1CwR7
序列生成包含给定长度的随机整数
function generate_array($count, $min, $max) {
$arr = array();
for ($i=0; $i<$count; $i++) {
$arr[$i] = rand($min, $max);
}
return $arr;
}
计算给定间隔的百分比(使用辅助函数):
function cnt($element, $arr){
$cnt = array_count_values($arr);
return $cnt[$element];
}
function percentages($min, $max, $arr) {
$total = sizeof($arr);
$occurences = 0;
while ($min < $max) {
if (!array_key_exists($min, $arr)) {
continue;
} else {
$occurences = $occurences + cnt($min, $arr);
}
$min++;
}
return $occurences/$total;
}
答案 2 :(得分:0)
将所有模拟值添加到数组中,并使用array_count_values获取所有唯一值。
function randomDigits($numDigits) {
$arrayRange = 1000;
if ($numDigits <= 0) {
return '';
} else{
$arr=array();
for($i=0; $i<$arrayRange; $i++){
$val=mt_rand(0, 50);
$arr[]=$val;
echo $val ." ";
}
echo "\n";
$arr=array_count_values($arr);
echo "Total Unique numbers:".count($arr);
}
}
$maxq = 100;
for ($i = 1; $i <= $maxq; $i++) {
randomDigits($i) . "<br>\n----<br>\n";
}