最好是Ruby
我需要一种方法来确定一个数组是否是一个"子阵列"当订单重要时,另一个数组
例如,
a = ["1", "4", "5", "7", "10"]
b = ["1", "4", "5"]
c = ["1", "5", "4"]
d = ["1", "5", "10"]
a includes b = true
a includes c = false
a include d = false
提前致谢。
答案 0 :(得分:4)
[b, c, d].map do |arr|
a.each_cons(arr.length).any?(&arr.method(:==))
end
#⇒ [true, false, false]
这绝对不是最高性能的解决方案,但对于不是很大的数组来说,它是可行的,而且重要的是可读性。
答案 1 :(得分:0)
a = ["1", "4", "5", "7", "10"]
b = ["1", "4", "5"]
c = ["1", "5", "4"]
d = ["1", "5", "10"]
def sub_set?(arr_a, arr_b)
arr_a.select.with_index do |a, index|
arr_b[index] == a
end == arr_b
end
puts "testing sub_set #{a.inspect} and #{c.inspect}"
puts sub_set?(a,c).inspect
答案 2 :(得分:0)
class Array
def includes(array)
return false if array.size > self.size
indexes = []
self.each_with_index {|e, i| indexes << i if e == array[0]}
p indexes
indexes.each do |i|
return true if self[i..i+array.size-1] == array
end
return false
end
end
p a.includes b
p a.includes c
p a.includes d
或者不那么虚假:))
class Array
def includes(array)
return false if array.size > self.size
indexes = each.with_index.select { |e, i| e == array[0] }.map(&:last)
indexes.each {|i| self[i..i+array.size-1] == array ? (return true) : (return false)}
end
end
p a.includes b
p a.includes c
p a.includes d
答案 3 :(得分:0)
你可以join
具有任意字符的元素然后比较字符串:
a.join(' ').match?(array.join(' '))
这适用于您提供的测试用例:
a.join(' ').match?(b.join(' '))
#=> true
a.join(' ').match?(c.join(' '))
#=> false
a.join(' ').match?(d.join(' '))
#=> false
但这不是一般解决方案,并且会因不同类型的数组而失败(请参阅注释以供进一步讨论)。