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

Ruby实现两个字符串数组的Subtract操作(元素顺序与位置无关)

Ruby Array Subtraction Ignoring Order & Position

Great question! When you say a "subtract" operation that ignores element order and position, you're probably looking for either a set-based difference (ignoring duplicates entirely) or a multiset-based difference (accounting for how many times each element appears). Let's break down both approaches in Ruby:

1. Set-Based Difference (Ignore Duplicates)

If you only care about which elements exist in the first array but not the second (and don't care about how many times they appear), converting your arrays to Set is the way to go. Ruby's Set class handles unordered, unique elements perfectly for this use case.

Example Code:

require 'set'

# Sample arrays
fruits1 = ["apple", "banana", "cherry", "apple"] # Duplicate "apple"
fruits2 = ["banana", "date"]

# Compute set difference: elements in fruits1 not present in fruits2
difference = (fruits1.to_set - fruits2.to_set).to_a

puts difference.inspect # Output: ["apple", "cherry"]

How it works:

  • to_set converts the array to an unordered collection of unique elements.
  • The - operator on Set returns a new set containing elements from the first set that aren't in the second.
  • Convert back to an array with to_a if you need the result in array form.

2. Multiset-Based Difference (Account for Element Counts)

If you need to preserve the number of occurrences (e.g., subtract one "apple" from two "apples" and keep one), you'll need to count element frequencies first, then compute the difference.

Example Code:

def multiset_subtract(arr1, arr2)
  # Count occurrences of each element in both arrays
  count1 = arr1.tally
  count2 = arr2.tally

  # Calculate remaining count for each element (only keep positive counts)
  remaining_counts = count1.each_with_object({}) do |(item, count), hash|
    hash[item] = count - (count2[item] || 0)
  end.select { |_, count| count > 0 }

  # Expand counts back into an array
  remaining_counts.flat_map { |item, count| [item] * count }
end

# Sample usage
arr1 = ["a", "b", "a", "c"]
arr2 = ["a", "b"]

result = multiset_subtract(arr1, arr2)
puts result.inspect # Output: ["a", "c"]

How it works:

  • tally (Ruby 2.7+) counts how many times each element appears in the array.
  • We subtract the count from the second array from the first, keeping only elements with a positive remaining count.
  • flat_map expands the count hash back into an array of elements.

Why Ruby's Built-in Array#- Isn't Enough

Note that Ruby's default Array#- operator is order-dependent: it removes the first occurrence of elements from the second array. For example:

["a", "b", "a"] - ["a"] # Returns ["b"], not ["a", "b"]

This doesn't meet your requirement of ignoring order/position, so using sets or frequency counting is necessary.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:14:19