2014-07-09 171 views
0

所以我有这个问题,我从1 - 10生成随机数然后显示数字,然后确定什么是重复。 BTW intNcases是数字的数量,不应超过20.这实际上是我们的任务,我真的很难与它请帮助。这是我的代码到目前为止。如何识别重复的号码

样本输出

箱子随机数是:7

随机数:4,2,1,1,4,3,2

:4,2,1,3

重复num别尔斯是:4,2,1

<html> 
    <body> 
    <?php 
     $intNcases = 5; 
     $hold = array(0,0,0); 
     $temp = array(0,0,0); 
     $rep = array(0,0,0); 
     $num = array(0,0,0); 
     $count = 1; 
     if($intNcases>20) 
     { 
      echo 'Error N cases is greater than 20'; 
     } 
     else 
     { 
      echo 'The number of case/s is: '. $intNcases; 
      echo '<br><br>'. 'Input'.'<br>'; 
      for($x=0;$x<$intNcases;$x++) 
      { 
       $N = rand(1,10); 
       echo $N. '<br>'; 

       $hold[$x] = $N; 
       $temp[$x] = $N; 
      } 

      echo 'OUTPUT<br>'; 

      for($d=0;$d<$intNcases;$d++) 
      { 
       for($j=1;$j<$intNcases;$j++) 
       { 
        if($hold[$d] == $temp[$j]) 
        { 
         $rep[$j-1] = $hold[$j-1]; 
         $hold[$j-1] = 0; 
        } 
        else 
        { 
         $num[$j-1] = $hold[$j-1]; 
        } 
       } 
       echo '#'.$count.' - '.$num[$d]. '<br>'; 
       $count++; 
      } 
      echo 'Repeating numbers are: '; 
      for($k=0;$k<sizeof($rep);$k++) 
      { 
       echo $rep[$k]. ' '; 
      } 
     } 

     ?> 
     </body> 
    </html> 
+0

使用舒适函数in_array:http://php.net/manual/en/function.in-array.php ..实际上在将元素推入数组之前。 – briosheje

+0

我的歉意 - 我没有很好地阅读这个问题。所以我的答案是使用和你一样的技巧。 –

+0

非常感谢你的回答帮助我很多 – user3819815

回答

0

也许你能做到这一点更容易与array_unique或array_shuffle或其他阵列功能

0

你可以试试这个。

$intcases = rand(1,20); 
$numbers = array(); 

echo 'Random number of cases: '. $intcases . '</br>'; 
echo 'Random numbers are: '; 
for($x=0;$x<$intcases;$x++) 
{ 
    $number = rand(1,10); 
    echo $number. ' '; 
    if(array_key_exists($number, $numbers)) 
    { 
     $numbers[$number] = $numbers[$number] + 1; 
    }else 
    { 
     $numbers[$number] = 1; 
    } 
} 
echo '</br>'; 



echo 'Numbers are: '; 
foreach($numbers as $number => $x) 
{ 
    echo $number . ' '; 
} 
echo '</br>'; 

echo 'Repeating numbers: '; 
foreach($numbers as $key => $value) 
{ 
    if($value > 1) 
    { 
     echo $key . ' '; 
    } 
} 
echo '</br>'; 
+0

让我编辑它,以便它符合你的示例输出。 – Rimble