You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. 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 false immediately—no need to do extra work.
  2. each_cons Method: Ruby's each_cons(n) iterates over the array, yielding consecutive chunks of n elements. For example, [1,3,8].each_cons(2) gives us [[1,3], [3,8]].
  3. any? Check: The any? method returns true as soon as it finds a chunk that matches our sequence. If none match, it returns false.

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 containing 5 will return true (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] as true, and [2,6,4] as false.

内容的提问来源于stack exchange,提问作者Ruby Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:43:31