Home > Article > Backend Development > How to find non-consecutive numbers in a sequence of numbers in php
In PHP development, it is often necessary to find discontinuous numbers in a sequence of numbers. How to realize this requirement quickly and efficiently? This article will explain it to you in detail.
1. Problem background
Find discontinuous numbers in a sequence of numbers, that is, find the numbers that have a certain interval from the next number after a certain number. For example, given a sequence [1, 2, 6, 7, 9, 12, 15, 17] and asked to find discontinuous numbers, assuming the interval is 4, the return value is [2, 9, 17].
2. Problem Analysis
To realize this requirement, we need to traverse the entire number sequence and do the following processing for each number:
In specific implementation, the following methods can be used:
Traverse the sequence of numbers and process each number.
The specific implementation code is as follows:
function findDiscontinuousNumbers($nums, $interval) { $result = []; $previous = null; foreach ($nums as $num) { if (!is_null($previous) && $num - $previous == $interval) { $result[] = $num; } $previous = $num; } return $result; } $nums = [1, 2, 6, 7, 9, 12, 15, 17]; $interval = 4; $result = findDiscontinuousNumbers($nums, $interval); print_r($result);
3. Code optimization
The above implementation can already meet the requirements, but it may not be efficient in actual use. . Consider the following optimization:
The optimized code is as follows:
function findDiscontinuousNumbers($nums, $interval) { $result = []; $previous = null; $last_discontinuous_index = null; // 上一次不连续数字的索引位置 for ($i = 0; $i < count($nums); ) { if (!is_null($previous)) { if ($nums[$i] - $previous == $interval) { $result[] = $nums[$i]; } else { $previous = $nums[$i]; $last_discontinuous_index = $i; } } else { $previous = $nums[$i]; $last_discontinuous_index = $i; } $i += ($i == $last_discontinuous_index + 1) ? 1 : $interval; } return $result; } $nums = [1, 2, 6, 7, 9, 12, 15, 17]; $interval = 4; $result = findDiscontinuousNumbers($nums, $interval); print_r($result);
IV. Summary
This article briefly introduces the method of finding discontinuous numbers in PHP and gives Basic implementation. In actual use, appropriate implementation methods and optimization measures should be selected according to different needs to achieve better performance and effects.
The above is the detailed content of How to find non-consecutive numbers in a sequence of numbers in php. For more information, please follow other related articles on the PHP Chinese website!