Who likes it? ( 6 kyu )

문제

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.

Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

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"

배열의 사람 수에따라 다른 문자열을 출력하는 문제

풀이

function likes(names) {
  switch ( names.length ) {
    case 0: return 'no one likes this';
    case 1: return `${names[0]} likes this`;
    case 2: return `${names[0]} and ${names[1]} like this`;
    case 3: return `${names[0]}, ${names[1]} and ${names[2]} like this`;
    default: return `${names[0]}, ${names[1]} and ${names.length-2} others like this`;
  }
}

코드워즈를 풀면서 처음으로 스위치 케이스를 사용함.

어려운 문젠 아닌듯

다른 사람의 풀이

똑같이 풀어서 안가져옴


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Tribonacci Sequence ( 6 kyu )  (0) 2017.11.28
Valid Braces ( 4 kyu )  (0) 2017.11.27
Unique In Order ( 6 kyu )  (0) 2017.11.26
Counting Duplicates ( 6 kyu )  (0) 2017.11.26
Vasya - Clerk ( 6 kyu )  (0) 2017.11.26

Unique In Order ( 6 kyu )

문제

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]

문자열에서 연속으로 중복되는 단어를 제거해 배열로 리턴하는 문제

풀이

var uniqueInOrder=function(iterable){
  if ( !iterable ) return [];
  let temp = iterable[0], result = [];
  for ( let i = 1; i < iterable.length; i++ ) {
    if ( iterable[i] !== temp ) {
      result.push(temp);
      temp = iterable[i];
    }
  }
  result.push(iterable[iterable.length-1])
  return result;
}

가장 윗줄은 빈 배열일 때 예외처리

temp에 문자가 바뀌면 등록해놓고 새로운 문자로 바뀔때마다 result배열에 푸시, 마지막 인덱스 푸시 후 리턴

다른 사람의 풀이

function uniqueInOrder(it) {
  var result = []
  var last

  for (var i = 0; i < it.length; i++) {
    if (it[i] !== last) {
      result.push(last = it[i])
    }
  }

  return result
}

비슷한데 뭔가 다름

배열에 푸시하는 방식이 새로움


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Valid Braces ( 4 kyu )  (0) 2017.11.27
Who likes it? ( 6 kyu )  (0) 2017.11.27
Counting Duplicates ( 6 kyu )  (0) 2017.11.26
Vasya - Clerk ( 6 kyu )  (0) 2017.11.26
Build a pile of Cubes ( 6 kyu )  (0) 2017.11.25

Counting Duplicates ( 6 kyu )

문제

Count the number of Duplicates

Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

Example

"abcde" -> 0 # no characters repeats more than once
"aabbcde" -> 2 # 'a' and 'b'
"aabBcde" -> 2 # 'a' occurs twice and 'b' twice (bandB)
"indivisibility" -> 1 # 'i' occurs six times
"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
"aA11" -> 2 # 'a' and '1'
"ABBA" -> 2 # 'A' and 'B' each occur twice

중복되는 단어의 개수를 리턴하는 간단한 문제

풀이

function duplicateCount(text){
  let obj = {}, count = 0;
  text = text.toLowerCase();
  for ( let i = 0; i < text.length; i++ ) {
    if ( obj[text[i]] ) {
      obj[text[i]]++;
    } else {
      obj[text[i]] = 1;
    }
  }
  for ( let j in obj ) {
    if ( obj[j] > 1 ) count++
  }
  return count;
}

obj에 단어 개수를 담아놓고, 1보다 크면 count를 하나씩 추가해서 리턴

다른 사람의 풀이

function duplicateCount(text){
  return (text.toLowerCase().split('').sort().join('').match(/([^])\1+/g) || []).length;
}

한 줄로 푸는게 역시 제일 멋있어


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Who likes it? ( 6 kyu )  (0) 2017.11.27
Unique In Order ( 6 kyu )  (0) 2017.11.26
Vasya - Clerk ( 6 kyu )  (0) 2017.11.26
Build a pile of Cubes ( 6 kyu )  (0) 2017.11.25
Take a Ten Minute Walk ( 6 kyu )  (0) 2017.11.24

Vasya - Clerk ( 6 kyu )

문제

The new “Avengers” movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollars bill. A “Avengers” ticket costs 25 dollars.

Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.

Can Vasya sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?

Return YES, if Vasya can sell a ticket to each person and give the change. Otherwise return NO.

Examples:

// === JavaScript ==

tickets([25, 25, 50]) // => YES
tickets([25, 100])
        // => NO. Vasya will not have enough money to give change to 100 dollars

25달러짜리 티켓을 파는데 잔돈이 부족하면 NO, 가능하다면 YES를 리턴

풀이

function tickets(peopleInLine){
  let obj = { price: 0 };
  for ( let i of peopleInLine ) {
    if ( i === 25 ) {
      obj.price += 25
    } else if ( i === 50 ) {
      obj.price -= 25
      if ( obj.price < 0 ) return "NO";
      obj.price += 50
    } else if ( i === 100 ) {
      obj.price -= 75
      if ( obj.price < 0 ) return "NO";
    }
  }
  return "YES";
}

if문으로 쭉 엮어서 현재 보유한 금액이 거스름돈보다 적으면 NO 리턴, 포문 탈줄시 YES 리턴

생각하는데 그래도 시간이 조금 걸렸음.

다른 사람의 풀이

죄다 스위치 케이스로 해놨는데, 복잡해서 걍 안읽어봄 ㅎㅎㅎ


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Unique In Order ( 6 kyu )  (0) 2017.11.26
Counting Duplicates ( 6 kyu )  (0) 2017.11.26
Build a pile of Cubes ( 6 kyu )  (0) 2017.11.25
Take a Ten Minute Walk ( 6 kyu )  (0) 2017.11.24
IQ Test ( 6 kyu )  (0) 2017.11.24

Build a pile of Cubes ( 6 kyu )

문제

Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.

You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?

The parameter of the function findNb (find_nb, find-nb, findNb) will be an integer m and you have to return the integer n such as n^3 + (n-1)^3 + … + 1^3 = m if such a n exists or -1 if there is no such n.

Examples:

findNb(1071225) --> 45
findNb(91716553919377) --> -1

1부터 결과값까지 세제곱의 합이 인자값이 되는 경우를 찾아 리턴, 없다면 -1 리턴

풀이

function findNb(m) {
  let sum = 0, i = 1;
  while ( sum < m ) {
    sum += Math.pow(i, 3);
    if ( sum === m ) {
      return i
    }
    i++
  }
  return -1;
}

sum에 1부터 세제곱의 합을 담고, sum이 m 보다 커질때까지 while문을 돌려 만약 m과 같은 값이 있다면 i를 리턴, 아니라면 -1을 리턴

다른 사람의 풀이

function findNb(m) {
  var n = 0
  while (m > 0) m -= ++n**3
  return m ? -1 : n
}

똑같지만 간결해보임.


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Counting Duplicates ( 6 kyu )  (0) 2017.11.26
Vasya - Clerk ( 6 kyu )  (0) 2017.11.26
Take a Ten Minute Walk ( 6 kyu )  (0) 2017.11.24
IQ Test ( 6 kyu )  (0) 2017.11.24
Duplicate Encoder ( 6 kyu )  (0) 2017.11.23

Take a Ten Minute Walk ( 6 kyu )

문제

You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones — everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. [‘n’, ‘s’, ‘w’, ‘e’]). You know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don’t want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.

Note: you will always receive a valid array containing a random assortment of direction letters (‘n’, ‘s’, ‘e’, or ‘w’ only). It will never give you an empty array (that’s not a walk, that’s standing still!).

동서남북으로 걸어서 출발점으로 돌아올 수 있는지 확인하는 문제, 걸음이 너무 짧거나 길면 false를 리턴

풀이

function isValidWalk(walk) {
  if ( walk.length > 10 || walk.length < 3 ) return false;
  let obj = { 'e': 0, 'w': 0, 's': 0, 'n': 0 };
  for ( let i in walk ) {
    obj[walk[i]]++
  }
  return obj['e'] === obj['w'] && obj['s'] === obj['n'] ? true : false;
}

우선 예외처리를 가장 윗줄에서 해주고

obj 객체로 동서남북을 카운트해서 동,서의 개수와 남,북의 개수가 같으면 true 리턴

다른 사람의 풀이

function isValidWalk(walk) {
  var dx = 0
  var dy = 0
  var dt = walk.length

  for (var i = 0; i < walk.length; i++) {
    switch (walk[i]) {
      case 'n': dy--; break
      case 's': dy++; break
      case 'w': dx--; break
      case 'e': dx++; break
    }
  }

  return dt === 10 && dx === 0 && dy === 0
}

스위치문으로 신기하게 풀어서 가져옴. 접근법은 크게 다르지 않은 듯 하다


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Vasya - Clerk ( 6 kyu )  (0) 2017.11.26
Build a pile of Cubes ( 6 kyu )  (0) 2017.11.25
IQ Test ( 6 kyu )  (0) 2017.11.24
Duplicate Encoder ( 6 kyu )  (0) 2017.11.23
Stop gninnipS My sdroW! ( 6 kyu )  (0) 2017.11.22

IQ Test ( 6 kyu )

문제

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number.

! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)

For example:

iqTest("2 4 7 8 10") => 3 // Third number is odd, while the rest of the numbers are even

iqTest("1 2 1 1") => 2 // Second number is even, while the rest of the numbers are odd

해당 배열에 홀수나 짝수 값이 1개만 있으면 해당 값이 몇 번째에 있는지 리턴하는 문제

풀이

function iqTest(numbers){
  let arr = numbers.split(' ').map(a => a%2);
  return arr.indexOf(0) === arr.lastIndexOf(0) ? arr.indexOf(0)+1 : arr.indexOf(1)+1;
}

arr에 기존 문자열을 배열로 쪼개 각 인자를 2로 나눈 나머지만 넣어주고

indexOf와 lastIndexOf를 비교해 한개만 있는 값의 인덱스 +1을 리턴

6 kyu 문제만 계속해서 포스팅 하는데 올리기에는 너무 쉬운 내용인 것 같기도 하지만 다른 사람들의 풀이를 보기 위해 올림..

다른 사람의 풀이

function iqTest(numbers){
  numbers = numbers.split(" ").map(function(el){return parseInt(el)});

  var odd = numbers.filter(function(el){ return el % 2 === 1});
  var even = numbers.filter(function(el){ return el % 2 === 0});

  return odd.length < even.length ? (numbers.indexOf(odd[0]) + 1) : (numbers.indexOf(even[0]) + 1);
}

풀고 보니까 저번에 푼 문제랑 똑같았다..하놔

필터쓰면 간단하게 풀 수 있는 문젠데, 또! 생각조차 못했음..

filter.. 메모..


+ Recent posts