我创建了一个循环,该循环返回两个值之间的随机数。很好。
但是现在我也希望脚本也返回以下值:两个相似数字之间的唯一数字的数量。
示例: 4 5 8 22 45 3 85 44 4 55 15 23
如您所见,有一个双精度数,即四个,中间有7个数字。因此,我希望脚本回显这两个数字,因此在这种情况下,它应回显7,但是如果列表中有更多双打,则应回显某些双打之间的所有数字。
这就是我所拥有的:
for ($x = 0; $x <= 100; $x++) {
$min=0;
$max=50;
echo rand($min,$max);
echo "<br>";
}
有人可以帮助我或指导我吗?我正在学习:)
谢谢!
答案 0 :(得分:2)
因此,您需要将脚本分为三个部分:
简单-无需打印循环的每个步骤,而是将它们保存到array(),退出循环,与其他对象一起分析每个项目,例如:
然后,打印两个数组(我将其命名为“结果”和“范围”)
更新: 这是解决方案,希望您喜欢:
$result = array(); #variable is set as array object
$ranges = array(); #same
# 1st part - collecting random numbers
for ($x = 0; $x < 20; $x++)
{
$min=0;
$max=50;
$result[] = rand($min,$max); #here's putting random number to array
}
$result_size = count($result); #variable which is containg size of $result array
# 2nd part - getting ranges between values
for ($i = 0; $i < $result_size; $i++)
{
for ($j = 0; $j < $result_size; $j++)
{
if($i == $j) continue; # we don't want to compare numbers with itself,so miss it and continue
else if($result[$i] == $result[$j])
{
$range = $i - $j; # get range beetwen numbers
if($range > 0 ) # this is for miss double results like 14 and -14 for same comparing
{
$ranges[$result[$i]] = $range;
}
}
}
}
#3rd part - priting results
echo("RANDOM NUMBERS:<br>");
foreach($result as $number)
{
echo ("$number ");
}
echo("<br><br>RANGES BETWEEN SAME VALUES:<br>");
foreach($ranges as $number => $range)
{
echo ("For numbers: $number range is: $range<br>");
}
以下是回显示例($ x设置为20):
RANDOM NUMBERS:
6 40 6 29 43 32 17 44 48 21 40 2 33 47 42 3 22 26 39 46
RANGES BETWEEN SAME VALUES:
For numbers: 6 range is: 2
For numbers: 40 range is: 9
答案 1 :(得分:0)
这是你的鱼:
将兰特放入数组$ list = array();和$ list [] = rand($ min,$ max);然后用两个for循环处理数组。
$min=0;
$max=50;
$list = array();
for ($x = 0; $x <= 100; ++$x) {
$list[] = rand($min,$max);
}
print "<pre>";print_r($list);print "</pre>";
$ranges = array();
$count = count($list);
for ($i = 0; $i < $count; ++$i) {
$a = $list[$i];
for ($j = $i+1; $j < $count; ++$j) {
$b = $list[$j];
if($a == $b) {
$ranges[] = $j-$i;
}
}
}
print "<pre>";print_r($ranges);print "</pre>";