无论顺序如何,检查数组是否已包含新集

时间:2014-10-02 19:49:34

标签: ruby arrays

我有一个包含对象的数组数组:

[ [A, B, C],
  [A, B, D],
  [B, C, D] ]

我想检查一下[B, A, C]之类的值是否无法添加,因为它并非我的目的所独有。数组中的现有数组不应该有任何重复(我已经处理过了)。

我尝试了以下代码,但它无效:

#if false, don't add to existing array
!big_array.sort.include? new_array.sort

我做错了什么?

4 个答案:

答案 0 :(得分:1)

您应该对大数组中的数组进行排序。不是大阵本身

!big_array.map(&:sort).include? new_array.sort

答案 1 :(得分:1)

require 'set'

a = [['a', 'b', 'c'],
     ['a', 'b', 'd'],
     ['b', 'c', 'd']]

as = a.map(&:to_set)

as.include? ['b', 'a', 'c'].to_set #=> true
as.include? ['b', 'a', 'e'].to_set #=> false

使用:

(as << row.to_set) unless as.include? row.to_set

然后完成:

as.to_a

鉴于您的评论,如果您将所有行添加到:

a = [['a', 'b', 'c'],
     ['a', 'b', 'd'],
     ['b', 'c', 'd'],
     ['a', 'c', 'b'],
     ['c', 'a', 'b'],
     ['e', 'a', 'b'],
     ['c', 'b', 'd']]

然后:

a.reverse
 .map(&:to_set)
 .uniq
 .map(&:to_a)
  #=> [["b", "c", "d"],
  #    ["e", "a", "b"],
  #    ["a", "b", "c"],
  #    ["a", "b", "d"]]
保留原始数组需要

reverse,但请注意,结果中不会保留排序。如果您希望保留修改后的a的排序:

a.each_with_object(Set.new) { |row,set| set << row.to_set }
 .map(&:to_a) 
  #=> [["a", "b", "c"],
  #    ["a", "b", "d"],
  #    ["b", "c", "d"],
  #    ["e", "a", "b"]]

答案 2 :(得分:0)

a = [
    ['a', 'b', 'c'],
    ['a', 'b', 'd'],
    ['b', 'c', 'd']
]

class Array
  def add_only_if_combination_does_not_exist_in(double_array)
    if double_array.map(&:sort).include?(self.sort)
      puts "Won't be added since it already exists!"
    else
      puts 'Will be added'
      double_array << self
    end
  end
end

['b', 'a', 'c'].add_only_if_combination_does_not_exist_in(a)
['b', 'a', 'f'].add_only_if_combination_does_not_exist_in(a) #=> Will be added
p a #=> [["a", "b", "c"], ["a", "b", "d"], ["b", "c", "d"], ["b", "a", "f"]]

答案 3 :(得分:0)

如果您不关心元素的顺序,请考虑使用Set类。

require 'set'

big_set = Set.new

big_set << Set.new(['a', 'b', 'c'])
# => #<Set: {#<Set: {"a", "b", "c"}>}>

big_set << Set.new(['c', 'b', 'a'])
# => #<Set: {#<Set: {"a", "b", "c"}>}>

big_set << Set.new(['d', 'a', 'b'])
# => #<Set: {#<Set: {"a", "b", "c"}>, #<Set: {"d", "a", "b"}>}>