Determining whether one array contains the contents of another array in ruby

前端 未结 11 1018
清歌不尽
清歌不尽 2021-02-09 03:06

In ruby, how do I test that one array not only has the elements of another array, but contain them in that particular order?

correct_combination = [1, 2, 3, 4, 5         


        
相关标签:
11条回答
  • 2021-02-09 03:51

    I would suggestion a for loop that compares each one

    @out_of_order_elements = []
    
    for i in 0.. @array_size do
      unless submission_array[i] == @correct_combination[i]
        @out_of_order_ids.push(@submission_array[i])
      end
    end 
    
    0 讨论(0)
  • 2021-02-09 03:54

    I would like to consider continuous sequence of elements from other array in container array and present this:-- code is inspired from the Sawa's code

    class Array
      def contain? other
       arr = self & other
       (arr.eql? other ) && ((self.index(arr.last) - self.index(arr.first)).eql?(other.size - 1))
      end
    end
    

    Result:--

    correct_combination = [1, 2, 3, 4, 5]
    [1, 5, 8, 2, 3, 4, 5].contain?(correct_combination) # => false
    [8, 10, 1, 2, 3, 4, 5, 9].contain?(correct_combination) # => true
    [1, 8, 2, 3, 4, 5].contain?(correct_combination) # => false
    
    0 讨论(0)
  • 2021-02-09 03:57

    This is what I came up with

    a = [1, 2, 3, 4, 5]
    b = [2, 3, 5]
    c = [3, 9]
    
    irb(main):037:0* (a + b).sort.uniq == a.sort.uniq
    => true
    irb(main):038:0> (a + c).sort.uniq == a.sort.uniq
    => false
    
    0 讨论(0)
  • 2021-02-09 03:57

    This is the best I could come up with. All the return calls are a bit ugly, but it should be quicker than doing a string comparison if it's large arrays.

    class Array
      def same?(o)
        if self.size == o.size
          (0..self.size).each {|i| return false if self[i] != o[i] }
        else
          return false
        end
    
        return true
      end
    end
    
    a = [1,2,3,4,5]
    b = [1, 5, 8, 2, 3, 4, 5]
    c = [1, 2, 6, 4, 5]
    
    puts a.same?(a.reverse) # => false
    puts a.same?(a) # => true
    puts a.same?(b) # => false
    puts a.same?(c) # => false
    
    0 讨论(0)
  • 2021-02-09 03:58

    You can use each_cons method:

    arr = [1, 2, 3, 4, 5]
    [1, 5, 8, 2, 3, 4, 5].each_cons(arr.size).include? arr
    

    In this case it will work for any elements.

    0 讨论(0)
提交回复
热议问题