Ruby数组特定值比较:如何检测目标元素是否连续无间隔排列
How to Check if a Sequence Appears Consecutively in a Target Array
Got it, let's tackle this problem step by step. The key here is verifying that our specified sequence (like a = [1,3]) shows up as an unbroken, ordered consecutive block within a target subarray. Here's how to implement this logic, using Ruby since you mentioned you're a Ruby Learner.
Core Logic Breakdown
First, let's clarify the rules to make sure we're on the same page:
- If the target array is shorter than our sequence, it's automatically impossible to contain the sequence → return
false. - We need to check every possible consecutive subarray of the target that has the exact same length as our sequence. If any of these subarrays matches our sequence exactly (order included), return
true. - If none of the consecutive subarrays match, return
false.
Ruby Implementation
Here's a reusable method that does exactly this:
def contains_consecutive_sequence?(target_array, sequence) # Handle edge cases first: empty sequence or target is too short return false if sequence.empty? || target_array.length < sequence.length # Check all consecutive chunks of the target that match the sequence's length target_array.each_cons(sequence.length).any? do |chunk| chunk == sequence end end
Let's Walk Through the Code
- Edge Case Handling: We first check if the sequence is empty (though your example doesn't use this, it's good practice) or if the target array is shorter than the sequence. In either case, return
falseimmediately—no need to do extra work. each_consMethod: Ruby'seach_cons(n)iterates over the array, yielding consecutive chunks ofnelements. For example,[1,3,8].each_cons(2)gives us[[1,3], [3,8]].any?Check: Theany?method returnstrueas soon as it finds a chunk that matches our sequence. If none match, it returnsfalse.
Testing Your Example
Let's test this method with your sample data to confirm it works:
a = [1,3] b = [[1],[1,3],[1,3,8],[4,1,3],[1,8,3],[3,1]] b.each do |subarray| result = contains_consecutive_sequence?(subarray, a) puts "#{subarray} #=> #{result}" end
Expected Output:
[1] #=> false [1,3] #=> true [1,3,8] #=> true [4,1,3] #=> true [1,8,3] #=> false [3,1] #=> false
Perfect—this matches exactly what you were expecting!
Bonus Edge Cases to Consider
- Single-element sequence: If your sequence is
[5], any target array containing5will returntrue(since a single element is inherently consecutive). - Longer sequences: For example, if your sequence is
[2,4,6], this method will correctly identify targets like[1,2,4,6,8]astrue, and[2,6,4]asfalse.
内容的提问来源于stack exchange,提问作者Ruby Learner
相关产品推荐
相关产品推荐

