見習村02 - Unique In Order

02 - Unique In Order

Don’t say so much, just coding…

Instruction

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:

1
2
3
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]

Ruby

Init

1
2
3
def unique_in_order(iterable)
# put your solution here
end

Sample Testing

1
Test.assert_equals(unique_in_order('AAAABBBCCDAABBB'), ['A','B','C','D','A','B'])

Javascript

Init

1
2
3
var uniqueInOrder = function(iterable){
// your code here - remember iterable can be a string or an array
}

Sample Testing

1
Test.assertSimilar(uniqueInOrder('AAAABBBCCDAABBB'), ['A','B','C','D','A','B'])

Thinking

想法(1): 從舉例可以看出會傳入的 iterable 的型態會是陣列、字串,所以需先判斷型態,否則後面能接的方法會有不能用的情況
想法(2): 分群的概念,如果後面的英文字跟前一個相同的話,只顯示一個
想法(3): 可以用空陣列塞值進去、或者是分群 selectuniq 的那個值

https://ithelp.ithome.com.tw/upload/images/20200917/20120826A5q7a8riTw.jpg
圖片來源:Unsplash Roman Bozhko

Hint & Reference

Solution

Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
// 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])
}