douxiong3245 2019-07-14 11:31
浏览 31
已采纳

有人可以帮我修复重复数字的匹配数量吗?

I have a script that creates two sets of numbers: 1. a list of random numbers 2. a list of match numbers of repeating numbers

But the list of match numbers of repeating numbers is not working properly.

Let me give an example: Random numbers 5-14-5-4-15-12-8-10-18-13-11-25-15-14-2-7-24-22-13-22-16-18-10-11-25-2-18-9-19-8-1-16-1-23-0-16-17-23-21-20-22-21-9-4-20-24-19-16-9-17

Match numbers 3-11-2-6-2-3-2-2-2-2-2-4-3-2-4-3-4-2-2-2-2-2-2-2-2-2

If you look at the random numbers you see the first match number is the correct. After three numbers we have a match so that match number is 3. Then we start counting from the 5 and the next match number is also correct which is 11 and ends at number 15. But then we should have a match after 2 numbers but this does not work out properly.

Can someone assist me here?

<?php
$existing = [];
$repeat_numbers = [];

for ($rnd=1;$rnd<=50;$rnd++)
{
$randoms[] = mt_rand(0,25);
}
echo implode('-',$randoms).PHP_EOL;

echo "<br><br>";

$i = 1;
 foreach($randoms as $rnd){
 if(in_array($rnd,$existing)){
     $repeat_numbers[] = $i;
     $i=1;
 }
 $existing[] = $rnd;
 $i++;
 }
echo implode('-',$repeat_numbers);
?>
  • 写回答

1条回答 默认 最新

  • dougui2254 2019-07-15 17:37
    关注

    As per your expected match, "The match numbers should be: 3-11-8-8-7-6-8"

    <?php
    $existing = [];
    $repeat_numbers = [];
    $randoms = explode('-','5-14-5-4-15-12-8-10-18-13-11-25-15-14-2-7-24-22-13-22-16-18-10-11-25-2-18-9-19-8-1-16-1-23-0-16-17-23-21-20-22-21-9-4-20-24-19-16-9-17');
    //print_r($randoms);
    $i = 0;
    foreach($randoms as $rnd){
       $i++; 
       if(in_array($rnd,$existing)){
           $repeat_numbers[] = $i;
           $i=1;
           $existing = [];
       }
       $existing[] = $rnd; 
    }
    echo implode('-',$repeat_numbers);
    ?>
    

    WORKING DEMO: https://3v4l.org/HbFnV

    Then just add this instead of hard coded $random string variable and use the rest of the code as usual.

    <?php
    $existing = [];
    $repeat_numbers = [];
    for ($rnd=1;$rnd<=50;$rnd++)
    {
      $randoms[] = mt_rand(0,25);  // see this block for generating randoms
    }
    $i = 0;
    foreach($randoms as $rnd){
       $i++; 
       if(in_array($rnd,$existing)){
           $repeat_numbers[] = $i;
           $i=1;
           $existing = [];
       }
       $existing[] = $rnd; 
    }
    echo implode('-',$repeat_numbers);
    ?>
    

    WORKING DEMO: https://3v4l.org/TvD4S

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?