-
[Codewars] Who likes it?Algorithm 2020. 10. 28. 09:46
<Codewars 6Kyu> Who likes it? 문제
www.codewars.com/kata/5266876b8f4bf2da9b000362/train/javascript
Codewars: Achieve mastery through challenge
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
[문제] Who likes it?
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.
example:
likes [] -- must be "no one likes this" likes ["Peter"] -- must be "Peter likes this" likes ["Jacob", "Alex"] -- must be "Jacob and Alex like this" likes ["Max", "John", "Mark"] -- must be "Max, John and Mark like this" likes ["Alex", "Jacob", "Mark", "Max"] -- must be "Alex, Jacob and 2 others like this"
페이스북이나 다른 sns에 있는 '좋아요'를 누른 사람을 표시해주는 문제다.
기본으로 빈 배열을 하나 만들고 '좋아요'를 누른 사람들을 그 배열 안에 차례대로 추가해주는 것 같다.
마지막으로 배열 안에 들어가 있는 사람들을 문자열로 형식에 맞춰서 리턴해주면 된다.
수도코드
1. 배열의 길이가 0, "no one likes this"를 리턴 2. 길이가 1, "이름 likes this"를 리턴 3. 길이가 2, "이름1 and 이름2 like this"를 리턴 4. 길이가 3, "이름1, 이름2 and 이름3 like this"를 리턴 5. 길이가 4 이상, "이름1, 이름2 and 2 others like this"를 리턴
풀이
function likes(names) { if(names.length === 0) { return "no one likes this" } else if(names.length === 1) { return `${names[0]} likes this` } else if(names.length === 2) { return `${names[0]} and ${names[1]} like this` } else if(names.length === 3) { return `${names[0]}, ${names[1]} and ${names[2]} like this` } else if(names.length > 3) { return `${names[0]}, ${names[1]} and ${names.length - 2} others like this` } }
통과
다른 풀이
function likes(names) { return { 0: 'no one likes this', 1: `${names[0]} likes this`, 2: `${names[0]} and ${names[1]} like this`, 3: `${names[0]}, ${names[1]} and ${names[2]} like this`, 4: `${names[0]}, ${names[1]} and ${names.length - 2} others like this`, }[Math.min(4, names.length)] }
'Algorithm' 카테고리의 다른 글
[프로그래머스] 약수의 합 (0) 2021.01.18 [Codewars] Valid Braces (0) 2020.11.16 [Codewars] Format a string of names like 'Bart, Lisa & Maggie' (0) 2020.11.08 [Codewars] Are they the "same"? (0) 2020.11.08 [Codewars] Create Phone Number (0) 2020.10.27