https://www.codewars.com/kata/54e6533c92449cc251001667
Codewars - Achieve mastery through coding practice and developer mentorship
A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!
www.codewars.com
DESCRIPTION:
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]
설명:
시퀀스를 인수로 받아 옆에 있는 원소와 같은 값을 가지지 않고 원래 순서를 유지하는 리스트를 반환하는 unique_in_order 함수를 구현하세요.
예시:
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]
풀이
배열을 하나 만들어 그 배열의 마지막 원소와 현재 시퀀스의 값이 다르면 그 배열에 넣어주었다.
코드
var uniqueInOrder=function(iterable){
const arr = [...iterable];
let result = [];
for(let i = 0; i < arr.length; i++){
if(result[result.length - 1] !== arr[i]) result.push(arr[i]);
}
return result;
}
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Playing with digits (6 kyu) / JavaScript (0) | 2022.12.13 |
---|---|
[Codewars] Decode the Morse code (6 kyu) / JavaScript (0) | 2022.12.12 |
[Codewars] Tribonacci Sequence (6 kyu) / JavaScript (0) | 2022.12.09 |
[Codewars] Grasshopper - Summation (8 kyu) / JavaScript (0) | 2022.12.08 |
[Codewars] String repeat (8 kyu) / JavaScript (0) | 2022.12.07 |
댓글