mplement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
For example:
1 2 3
unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] unique_in_order([1,2,2,3,3]) == [1,2,3]
Answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
def (iterable) arr = [] base_arr = [] if iterable.class .to_s == "String" base_arr = iterable.chars else base_arr = iterable end base_arr.each {|item| arr << item if arr[-1 ] != item} return arr end def (iterable) (iterable.is_a?(String) ? iterable.chars : iterable).chunk { |x| x }.map(&:first ) end def (seq) (0 ...seq.length).reduce([]) {|a, i| seq[i] != a.last ? a << seq[i] : a } end def (iterable) it_array= [] iterable.length.times do |x| it_array << iterable[x] if iterable[x] != iterable[x+1 ] end it_array end
近期评论