使用PHP识别重复模式


Identify repeating pattern using PHP

我需要找到大于特定浮点值的记录数,并找到重复次数最多的数据组。例如,我有下面的数据,我需要找到有多少条目的值>4。

 1.5
  1.7
    4.5
    4.7
    4.8
    1.4
    4.5
    4.9

在上述数据中,大于4的值的最长连续重复为4.5、4.7、4.8。因此,我希望返回的总数应该是3。正如你所看到的,这个模式在4.8之后中断,因为这个数字是1.4以上。有没有办法识别这种模式?

试试这个,我在这里使用了一个数组:

$arr = array(
        0 => '1.5',
        1 => '1.7',
        2 => '4.5',
        3 => '4.7',
        4 => '4.8',
        5 => '1.4',
        6 => '4.5',
        7 => '4.9'
      );
      $chk_val = 4; // value which is checking
      $cnt = 0;$inc = 0;
      foreach ($arr as $i => $val) {
        if ($val > $chk_val) {
          $inc++;
          if ($inc > $cnt) { $cnt = $inc;}
        } else {
          $inc = 0;
        }
      }
      echo $cnt;

尝试这个

$n = 4; // number to check
$count = 0;
$max = 0;
$ele = array(1.5, 1.7, 4.5, 4.7, 4.8, 1.4, 4.5, 4.9);
for ($i = 0; $i < count($ele); $i++) {
  if ($ele[$i] >= $n) {  // check for greater element than given number
    $count++;    // increase consecutive counter variable 
    $arr[$max] = $count; //save continues max counter to array
  } else {
    $count = 0; //reset consecutive counter 
    $max++;
  }    
}
echo max($arr);

快速且肮脏。。。

function findNums($nums, $min = 4) {
  $groups = array();
  $groupcounts = array();
  $groupindex = 0;
  foreach($nums as $num) {
    if($num > $min) {
      $groups[$groupindex][] = $num;
      if(array_key_exists($groupindex, $groupcounts)) {
        $groupcounts[$groupindex]++;
      } else {
        $groupcounts[$groupindex] = 1;
      }
    } else {
      $groupindex++;
    }
  }
  return array($groupcounts, $groups);
}
// $your_numbers is your list
$nums = array_map('trim', explode("'n", $your_numbers));
$result = findNums($nums);
$counts = $result[0];
$maxcount = max($counts);
$groups = $result[1];
echo "max count is ".$maxcount." with values:'n";
$key = array_search($maxcount, $counts);
var_dump($groups[$key]);