Don't say so much, just coding...
Implement 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:
uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
uniqueInOrder('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D']
uniqueInOrder([1,2,2,3,3]) == [1,2,3]
def unique_in_order(iterable)
# put your solution here
end
Test.assert_equals(unique_in_order('AAAABBBCCDAABBB'), ['A','B','C','D','A','B'])
var uniqueInOrder = function(iterable){
// your code here - remember iterable can be a string or an array
}
Test.assertSimilar(uniqueInOrder('AAAABBBCCDAABBB'), ['A','B','C','D','A','B'])
想法(1): 從舉例可以看出會傳入的 iterable
的型態會是陣列、字串,所以需先判斷型態,否則後面能接的方法會有不能用的情況
想法(2): 分群的概念,如果後面的英文字跟前一個相同的話,只顯示一個
想法(3): 可以用空陣列塞值進去、或者是分群 select
取 uniq
的那個值
# Solution 1
def unique_in_order(iterable)
(iterable.is_a?(String) ? iterable.split('') : iterable)
.chunk{ |s| s }
.map(&:first)
end
# Solution 2
def unique_in_order(iterable)
(iterable.is_a?(String) ? iterable.chars : iterable)
.chunk { |s| s }
.map(&:first)
end
# Solution 3
def unique_in_order(iterable)
iterable.is_a?(String) ? iterable.squeeze.split('') : iterable.uniq
end
// Solution 1
var uniqueInOrder = function(iterable){
var result = [];
for(i = 0; i < iterable.length; i++) {
if (iterable[i] != iterable[i+1]) result.push(iterable[i]);
}
return result;
}
// Solution 2
var uniqueInOrder = function(iterable){
return [...iterable].filter((i, index) => i !== iterable[index-1])
}