Simple Pig Latin ( 5 kyu )

문제

Move the first letter of each word to the end of it, then add “ay” to the end of the word. Leave punctuation marks untouched.

Examples

pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
pigIt('Hello world !');     // elloHay orldWay !

각 단어의 앞을 뒤로 옮기고 ay를 붙여 리턴하는 문제

풀이

function pigIt(str){
  let result = [];
  let arr = str.split(' ');
  for ( let i = 0; i < arr.length; i++ ) {
    result.push(arr[i].slice(1, arr[i].length) + arr[i][0] + 'ay')
  }
  return result.join(' ');
}

arr에 각 단어별로 쪼개 새로운 배열을 만들고 합쳐서 리턴

다른 사람의 풀이

function pigIt(str){
  return str.split(' ').map(function(el){
    return el.slice(1) + el.slice(0,1) + 'ay';
  }).join(' ');
}

map 쓰면 되는거네


Valid Parentheses ( 5 kyu )

문제

Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it’s invalid.

Examples

"()"              =>  true
")(()))"          =>  false
"("               =>  false
"(())((()())())"  =>  true

Constraints

0 <= input.length <= 100

You may assume that the input string will only contain opening and closing parenthesis and will not be an empty string.

주어진 문자열이 올바른 괄호쌍으로 이루어졌는지 판별하는 문제

풀이

function validParentheses(parens){
  while ( parens.indexOf('()') !== -1 ) {
    parens = parens.slice(0, parens.indexOf('()')).concat(parens.slice(parens.indexOf('()')+2, parens.length))
  }
  return (parens === '')
}

while문으로 ()를 계속해서 지워나가고 문자열이 비었다면 true 남아있다면 false 리턴

다른 사람의 풀이

function validParentheses(parens){
  var indent = 0;

  for (var i = 0 ; i < parens.length && indent >= 0; i++) {
    indent += (parens[i] == '(') ? 1 : -1;    
  }

  return (indent == 0);
}

(면 +1 )면 -1을 더해서 0이면 true를 리턴하는 방법


Replace With Alphabet Position ( 6 kyu )

문제

Welcome.

In this kata you are required to, given a string, replace every letter with its position in the alphabet.

If anything in the text isn’t a letter, ignore it and don’t return it.

a being 1, b being 2, etc.

As an example:

alphabet_position("The sunset sets at twelve o' clock.")

Should return “20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11” as a string.

알파벳을 숫자로 치환해 리턴하는 문제

풀이

function alphabetPosition(text) {
  let result = '';
  let arr = text.toLowerCase().split(' ').join('').split('');
  for ( let i = 0; i < arr.length; i++ ) {
    if ( arr[i].charCodeAt(0) >= 97 && arr[i].charCodeAt(0) <= 122 ) {
      result += arr[i].charCodeAt(0)-96 + ' '
    }
  }
  return result.substring(0, result.length-1);
}

아스키코드로 변환한 뒤에 96만큼 빼준 값을 문자열에 추가

다른 사람의 풀이

똑같음


Product of consecutive Fib numbers ( 5 kyu )

문제

The Fibonacci numbers are the numbers in the following integer sequence (Fn):

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, …
such as

F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
Given a number, say prod (for product), we search two Fibonacci numbers F(n) and > > F(n+1) verifying

F(n) * F(n+1) = prod.
Your function productFib takes an integer (prod) and returns an array:

[F(n), F(n+1), true] or {F(n), F(n+1), 1} or (F(n), F(n+1), True)
depending on the language if F(n) * F(n+1) = prod.

If you don’t find two consecutive F(m) verifying F(m) * F(m+1) = prodyou will return

[F(m), F(m+1), false] or {F(n), F(n+1), 0} or (F(n), F(n+1), False)
F(m) being the smallest one such as F(m) * F(m+1) > prod.

Examples

productFib(714) # should return [21, 34, true], 
                # since F(8) = 21, F(9) = 34 and 714 = 21 * 34

productFib(800) # should return [34, 55, false], 
                # since F(8) = 21, F(9) = 34, F(10) = 55 and 21 * 34 < 800 < 34 * 55

피보나치 수열중 연속된 수의 곱으로 인자 값이 나올수 있는지 판별하는 문제

풀이

function productFib(prod){
  let arr = [0, 1], multi = 0, i = 2;
  while ( multi <= prod ) {
    arr[i] = arr[i-1] + arr[i-2];
    multi = arr[i]*arr[i-1];
    if ( multi === prod ) return [arr[i-1], arr[i], true]
    i++
  }
  return [arr[i-2], arr[i-1], false]
}

피보나치 수열을 arr에 담고, 연속된 수의 곱을 multi에 담아 prod보다 작을 때까지 반복하고, 일치하면 해당 값을 리턴, 일치하지 않다면 다음 두개의 수를 리턴

다른 사람의 풀이

function productFib(prod){
  var n = 0;
  var nPlus = 1;  
  while(n*nPlus < prod) {
    nPlus = n + nPlus;
    n = nPlus - n;
  }
  return [n, nPlus, n*nPlus===prod];
}

따로 공간을 만들지 않고도 이런식으로 풀이가 가능하군


Give me a Diamond ( 6 kyu )

문제

You need to return a string that displays a diamond shape on the screen using asterisk (“*”) characters. Please see provided test cases for exact output format.

The shape that will be returned from print method resembles a diamond, where the number provided as input represents the number of ’s printed on the middle line. The line above and below will be centered and will have 2 less ’s than the middle line. This reduction by 2 ’s for each line continues until a line with a single is printed at the top and bottom of the figure.

Return null if input is even number or negative (as it is not possible to print diamond with even number or negative number).

Please see provided test case(s) for examples.

다이아몬드 별찍기, n이 0이하거나 짝수면 null을 리턴

풀이

function diamond(n){
  if ( n < 1 || n%2 === 0 ) return null
  let result = '', mid = Math.ceil(n/2);
  for ( let i = 1; i <= n; i++ ) {
    if ( i <= mid ) {
      result += ' '.repeat(mid-i) + '*'.repeat(2*i-1) + '\n'
    } else {
      result += ' '.repeat(i-mid) + '*'.repeat(2*(n-i)+1) + '\n'
    }
  }
  return result;
}

mid를 기준점으로 잡고, repeat으로 별찍기 구성

어렵지는 않은데 2*(n-i)+1 생각해내는데 시간이 걸림 ㅋㅋ;

다른 사람의 풀이

function diamond(n){
  if( n%2==0 || n<1 ) return null
  var x=0, add, diam = line(x,n);
  while( (x+=2) < n ){
    add = line(x/2,n-x);
    diam = add+diam+add;
  }
  return diam;
}//z.

function repeat(str,x){return Array(x+1).join(str); }
function line(spaces,stars){ return repeat(" ",spaces)+repeat("*",stars)+"\n"; }

좋은풀이인지는 잘모르겠지만 신기하게 풀어서 가져옴


Take a Number And Sum Its Digits Raised To The Consecutive Powers And ….¡Eureka!! ( 6 kyu )

문제

The number 89 is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What’s the use of saying “Eureka”? Because this sum gives the same number.

In effect: 89 = 8^1 + 9^2

The next number in having this property is 135.

See this property again: 135 = 1^1 + 3^2 + 5^3

We need a function to collect these numbers, that may receive two integers a, b that defines the range [a, b] (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.

Let’s see some cases:

sumDigPow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]

sumDigPow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]

첫번째와 두번째 인자 사이에 해당 값이 각자릿수의 제곱합과 같은 수를 찾아 리턴하는 문제

풀이

function sumDigPow(a, b) {
  let result = [], arr, sum = 0;
  for ( let i = a; i <= b; i++ ) {
    arr = i.toString().split('').map(Number);
    sum = 0;
    for ( let j = 0; j < arr.length; j++ ) {
      sum += Math.pow(arr[j], j+1);
    }
    if ( i === sum ) {
      result.push(i);
    }
  }
  return result;
}

포문 두개로 구성해서 그냥 노가다 식으로 짰는데, 통과는 되었지만 좋은 코드는 아닌 것 같다.

다른 사람의 풀이

function sumDigPow(a, b) {
  var ans = [];
  while(a <= b){
    if(a.toString().split('').reduce((x,y,i)=>x + +y ** (i + 1),0) == a)
      ans.push(a);
    a++;
  }
  return ans;
}

접근은 같지만 조금더 간결하게 코드를 작성하는 방법

언제봐도 리듀스는 너무 어려움

리듀스 세번째 인자는 인덱스.. 메모..


Find the missing letter ( 6 kyu )

문제

Find the missing letter

Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.

You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.
The array will always contain letters in only one case.

Example:

['a','b','c','d','f'] -> 'e'
['O','Q','R','S'] -> 'P'

연속된 알파벳 중 빠진 단어를 리턴하는 문제

풀이

function findMissingLetter(array) {
  let code = array[0].charCodeAt(0);
  for ( let i = 1; i < array.length; i++ ) {
    if ( code+1 === array[i].charCodeAt(0) ) {
      code = code+1
    } else {
      return String.fromCharCode(code+1);
    }
  }
}

가장 앞의 알파벳의 아스키코드를 code에 담고 포문을 돌려 다음 알파벳인지 비교하는 방법

만약 비어있다면 해당 알파벳을 리턴

다른 사람의 풀이

풀이 방법이 다 똑같음


Maximum subarray sum ( 5 kyu )

문제

The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:

maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
// should be 6: [4, -1, 2, 1]

Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.

Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.

배열에서 연속된 원소의 합이 최대일 때를 구하는 문제

풀이

var maxSequence = function(arr){
  let max = 0, sum = 0, j;
  for ( let i = 0; i < arr.length; i++ ) {
    sum = 0;
    j = i;
    while ( sum <= max ) {
      sum += arr[j]
      if ( sum > max ) {
        max = sum;
      }
      j++;
    }
  }
  return max
}

for, while로 a에 b의 원소들이 없을때까지 반복해서 리턴

다른 사람의 풀이

var maxSequence = function(arr){
  var min = 0, ans = 0, i, sum = 0;
  for (i = 0; i < arr.length; ++i) {
    sum += arr[i];
    min = Math.min(sum, min);
    ans = Math.max(ans, sum - min);
  }
  return ans;
}

포문 하나로 해결.

이게 더 좋은 코드


+ Recent posts