Create Phone Number ( 6 kyu )

문제

Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.

Example:

createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"

The returned format must be correct in order to complete this challenge.
Don’t forget the space after the closing parenthesis!

주어진 배열로 형식에 맞게 문자열로 리턴

풀이

function createPhoneNumber(numbers){
  return `(${numbers.slice(0,3).join('')}) ${numbers.slice(3,6).join('')}-${numbers.slice(6, 10).join('')}`;
}

slice, join으로해서 작성

다른 사람의 풀이

function createPhoneNumber(numbers){
  var format = "(xxx) xxx-xxxx";

  for(var i = 0; i < numbers.length; i++)
  {
    format = format.replace('x', numbers[i]);
  }

  return format;
}

replace로 할수가 있는건 신기하네


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

Sort the odd ( 6 kyu )  (0) 2017.12.06
Is a number prime? ( 6 kyu )  (0) 2017.12.06
Convert string to camel case ( 5 kyu )  (0) 2017.12.05
Human Readable Time ( 5 kyu )  (0) 2017.12.05
Simple Pig Latin ( 5 kyu )  (0) 2017.12.05

Convert string to camel case ( 5 kyu )

문제

Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized.

Examples:

// returns "theStealthWarrior"
toCamelCase("the-stealth-warrior") 

// returns "TheStealthWarrior"
toCamelCase("The_Stealth_Warrior")

풀이

function toCamelCase(str){
  while ( str.indexOf('-') !== -1 ) {
    str = str.slice(0, str.indexOf('-')) + str[str.indexOf('-')+1].toUpperCase() + str.slice(str.indexOf('-')+2, str.length)
  }
  while ( str.indexOf('_') !== -1 ) {
    str = str.slice(0, str.indexOf('_')) + str[str.indexOf('_')+1].toUpperCase() + str.slice(str.indexOf('_')+2, str.length)
  }
  return str
}

while문으로 와 -가 없어질때까지 반복문을 돌면서 를 지우고 _다음 단어를 대문자로 변경해서 리턴

다른 사람의 풀이

function toCamelCase(str){
  return str.replace(/[-_](.)/g, (_, c) => c.toUpperCase());
}

정규식으로 될거같았는데 익숙하지 않아서 고민하다가 결국 못했는데, 이렇게 쓰면 되는군


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

Is a number prime? ( 6 kyu )  (0) 2017.12.06
Create Phone Number ( 6 kyu )  (0) 2017.12.06
Human Readable Time ( 5 kyu )  (0) 2017.12.05
Simple Pig Latin ( 5 kyu )  (0) 2017.12.05
Valid Parentheses ( 5 kyu )  (0) 2017.12.05

Human Readable Time ( 5 kyu )

문제

Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS)

HH = hours, padded to 2 digits, range: 00 - 99
MM = minutes, padded to 2 digits, range: 00 - 59
SS = seconds, padded to 2 digits, range: 00 - 59
The maximum time never exceeds 359999 (99:59:59)

You can find some examples in the test fixtures.

주어진 초를 시,분,초로 출력하는 문제

풀이

function humanReadable(seconds) {
  let result = '',h = 0, m = 0 , s = 0;
  h = parseInt(seconds/3600);
  seconds = seconds - 3600*h
  m = parseInt(seconds/60);
  seconds = seconds - 60*m;
  s = seconds;
  h < 10 ? result += '0' + h + ':' : result += h + ':';
  m < 10 ? result += '0' + m + ':' : result += m + ':';
  s < 10 ? result += '0' + s : result += s;
  return result
}

3600, 60으로 나눈 몫을 h,m, 나머지를 s에 담아 리턴

처음에 어렵게 생각해서 while문 돌리고 난리쳤는데 그럴 필요가 없었음.

다른 사람의 풀이

unction humanReadable(seconds) {
  var pad = function(x) { return (x < 10) ? "0"+x : x; }
  return pad(parseInt(seconds / (60*60))) + ":" +
         pad(parseInt(seconds / 60 % 60)) + ":" +
         pad(seconds % 60)
}

내 코드는 쓰면서도 너무 중복이 많았는데 효율적으로 잘 잡은 것 같음.

clever 130개 받을만 한 코드


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"; }

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


+ Recent posts