duanjianxu4288 2019-07-24 22:36
浏览 100

如何在连续的行上找到重复单词的最大次数?

I have files which have contents that contain only "win" or "loss" like so:

win
win
loss
loss
loss
loss
win
loss
win
win
win
win
win
loss
loss
win
win

I would like to find the largest winning streak, which is the largest number of times that the word "win" has appeared on consecutive lines. In the above example, "win" appears consecutively 2 , 1, 5 and 2 times. so the largest win streak would be "5".

How can i use the Linux terminal or PHP to calculate this? The only way i can think to do it is to look for "win" then use a large number of nested if statements to check the next line, but if the win streak was over 100+ then this would result in large amounts of code. Is their examples of how this can be done more efficiently?

  • 写回答

5条回答 默认 最新

  • dongxifu5009 2019-07-24 23:58
    关注

    As there's still no PHP solution given to this question, and admittedly slightly more verbose than the solutions given in the comments... This might help:

    <?php
    $content = file_get_contents('winloss.txt');
    $arr = explode("
    ", $content);
    $rep = repetition($arr);
    echo $rep['response'];
    
    function repetition(array $arr, $str1 = 'win', $str2 = 'loss')
    {
        $prevVal = null;
        $count = 1;
        foreach($arr as $key => $value) {
            if($prevVal == $value) {
                $count++;
                $storeRep[$value][] = $count;
            } else {
                $count = 1;
            }
            $prevVal = $value;
        }
        $maxConsec[$str1] = max($storeRep[$str1]);
        $maxConsec[$str2] = max($storeRep[$str2]);
        $maxConsec['response'] = "largest winning streak : " . $maxConsec[$str1];
        return $maxConsec;
    }
    

    output: largest winning streak : 5

    var_dump($rep):

    array(3) {
      ["win"]=>
      int(5)
      ["loss"]=>
      int(4)
      ["response"]=>
      string(26) "largest winning streak : 5"
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办