Array Deep Count ( 6 kyu )

문제

Array.prototype.length will give you the number of top-level elements in an array.

Your task is to create a function deepCount that returns the number of ALL elements within an array, including any within inner-level arrays.

For example:

deepCount([1, 2, 3]);
//>>>>> 3
deepCount(["x", "y", ["z"]]);
//>>>>> 4
deepCount([1, 2, [3, 4, [5]]]);
//>>>>> 7

배열에서 내부의 배열 인자개수까지 모두 세는 문제

풀이

function deepCount(a){
  let count = 0;
  const recursion = arr => {
    count += arr.length;
    for ( let i of arr ) {
      if ( Array.isArray(i) ) {
        recursion(i);
      }
    }
  }
  recursion(a);
  return count;
}

재귀를 통해 인자가 배열이면 함수를 다시 호출하는 방법

다른 사람의 풀이

function deepCount(a){
  return a.reduce((s,e)=>s+(Array.isArray(e)?deepCount(e):0),a.length);
}

위에 있는 코드를 압축해놓으면 딱 이모양인데 멋있는 코드


Fibonacci, Tribonacci and friends ( 6 kyu )

문제

If you have completed the Tribonacci sequence kata, you would know by now that mister Fibonacci has at least a bigger brother. If not, give it a quick look to get how things work.

Well, time to expand the family a little more: think of a Quadribonacci starting with a signature of 4 elements and each following element is the sum of the 4 previous, a Pentabonacci (well Cinquebonacci would probably sound a bit more italian, but it would also sound really awful) with a signature of 5 elements and each following element is the sum of the 5 previous, and so on.

Well, guess what? You have to build a Xbonacci function that takes a signature of X elements - and remember each next element is the sum of the last X elements - and returns the first n elements of the so seeded sequence.

xbonacci {1,1,1,1} 10 = {1,1,1,1,4,7,13,25,49,94}
xbonacci {0,0,0,0,1} 10 = {0,0,0,0,1,1,2,4,8,16}
xbonacci {1,0,0,0,0,0,1} 10 = {1,0,0,0,0,0,1,2,3,6}
xbonacci {1,1} produces the Fibonacci sequence

피보나치를 확장시켜 주어진 배열의 n번째 항까지 구해 리턴하는 문제

풀이

function Xbonacci(signature,n){
  let arr = signature.slice(), sum;
  for ( let i = 0; i < n-signature.length; i++ ) {
    sum = 0;
    for ( let j = i; j < i+signature.length; j++ ) {
      sum += arr[j]
    }
    arr.push(sum)
  }
  return arr.slice(0, n);
}

주어진 기본 배열을 복사해 다음 항은 이전 항들의 합으로 구해지도록 함

다른 사람의 풀이

const Xbonacci = (sig, n) => {
  let len = sig.length;
  for (let i = len; i < n; i++) 
    sig[i] = sig.slice(i - len).reduce((a, b) => a + b);
  return sig.slice(0, n);
}]

reduce를 사용해 이전항들의 합을 다음 항에 넣어주는 방법


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

Simple reversed parenthesis ( 6 kyu )  (0) 2018.01.09
Array Deep Count ( 6 kyu )  (0) 2017.12.27
What is the growth? ( 6 kyu )  (0) 2017.12.22
Dashatize it ( 6 kyu )  (0) 2017.12.20
String average ( 6 kyu )  (0) 2017.12.19

What is the growth? ( 6 kyu )

문제

Write the function getGrowth(), which accepts an arbitrary number of comma separated integers and returns the difference between each subsequent and previous number in the series, as a string.

The function must return a string value where each “growth instance” is separated by a comma followed by a space character.

Example 1:

getGrowth(1, 2, 3)  // returns the string: "1 (+0, +0%), 2 (+1, +100%), 3 (+1, +50%)"

배열이 들어오면 이전값과 비교해서 변화를 적어 리턴하는 문제

풀이

function getGrowth(...args){
  let result = `${args[0]} (+0, +0%), `;
  for ( let i = 1; i < args.length; i++ ) {
    if ( args[i]-args[i-1] >= 0 ) {
      result += `${args[i]} (+${args[i]-args[i-1]}, +${Math.round((args[i]-args[i-1])/args[i-1]*100)}%), `
    } else {
      result += `${args[i]} (${args[i]-args[i-1]}, ${Math.round((args[i]-args[i-1])/args[i-1]*100)}%), `
    }
  }
  return result.slice(0, result.length-2);
}

그냥 써져있는대로 맞춰 씀..

다른 사람의 풀이

비슷함


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

Array Deep Count ( 6 kyu )  (0) 2017.12.27
Fibonacci, Tribonacci and friends ( 6 kyu )  (0) 2017.12.23
Dashatize it ( 6 kyu )  (0) 2017.12.20
String average ( 6 kyu )  (0) 2017.12.19
Array Helper ( 6 kyu )  (0) 2017.12.19

Dashatize it ( 6 kyu )

문제

Given a number, return a string with dash’-‘marks before and after each odd integer, but do not begin or end the string with a dash mark.

Ex:

dashatize(274) -> '2-7-4'
dashatize(6815) -> '68-1-5'

홀수는 앞뒤로 대시를 붙여 리턴하는 문제

풀이

function dashatize(num) {
  let str = num.toString();
  let result = '';
  for ( let i = 0; i < str.length; i++ ) {
    str[i] % 2 === 1 ? result += `-${str[i]}-` : result += str[i];
  }
  while ( result[0] === '-' ) {
    result = result.slice(1)
  }
  while ( result[result.length-1] === '-' ) {
    result = result.slice(0, result.length-1);
  }
  return result.replace(/--/g, '-');
};

문자열로 변환 후 홀수인 경우에 대시를 앞뒤로 붙이고 마지막에 앞뒤를 자르고, 두개인 경우를 한개로 바꿔주고 리턴

다른 사람의 풀이

function dashatize(num) {
  return String(num)
    .replace(/([13579])/g, "-$1-")
    .replace(/--+/g, "-")
    .replace(/(^-|-$)/g, "")
}

신기한 정규식


String average ( 6 kyu )

문제

You are given a string of numbers between 0-9. Find the average of these numbers and return it as a floored whole number (ie: no decimal places) written out as a string. Eg:

“zero nine five two” -> “four”

If the string is empty or includes a number greater than 9, return “n/a”

문자로 써져있는 숫자의 평균을 문자로 리턴하는 문제

풀이

function averageString(str) {
  const num = ['zero', 'one','two','three','four','five','six','seven','eight','nine'];
  const arr = str.split(' ');
  let result = 0;
  for ( let i = 0; i < arr.length; i++ ) {
    if ( num.indexOf(arr[i]) === -1 ) return 'n/a';
    result += num.indexOf(arr[i]);
  }
  return num[parseInt(result/arr.length)];
}

num에 문자를 넣고 indexOf로 숫자를 카운트,

9보타 큰 경우는 예외처리로 n/a를 리턴하도록 함

다른 사람의 풀이

똑같음


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

What is the growth? ( 6 kyu )  (0) 2017.12.22
Dashatize it ( 6 kyu )  (0) 2017.12.20
Array Helper ( 6 kyu )  (0) 2017.12.19
Simple Fun #290: Sum Of Threes ( 6 kyu )  (0) 2017.12.18
RGB To Hex Conversion ( 5 kyu )  (0) 2017.12.11

Array Helper ( 6 kyu )

문제

var numbers = [1, 2, 3, 4, 5];
numbers.square(); // must return [1, 4, 9, 16, 25]
numbers.cube(); // must return [1, 8, 27, 64, 125]
numbers.average(); // must return 3
numbers.sum(); // must return 15
numbers.even(); // must return [2, 4]
numbers.odd(); // must return [1, 3, 5]

배열의 메서드를 구현하는 문제

풀이

// TODO
Array.prototype.square = function () {
  return this.map( a => { return a*a } );
}

Array.prototype.cube = function () {
  return this.map( a => { return a*a*a } );
}

Array.prototype.sum = function () {
  return this.length === 0 ? 0 : this.reduce((a,b) => { return a+b } );
}

Array.prototype.average = function () {
  return this.length === 0 ? NaN : this.reduce((a,b) => { return a+b } )/this.length;
}

Array.prototype.even = function () {
  console.log(this)
  return this.filter( a => { return a % 2 === 0 } );
}

Array.prototype.odd = function () {
  return this.filter( a => { return a % 2 === 1 } );
}

설명이 필요없따

다른 사람의 풀이

똑같음


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

Dashatize it ( 6 kyu )  (0) 2017.12.20
String average ( 6 kyu )  (0) 2017.12.19
Simple Fun #290: Sum Of Threes ( 6 kyu )  (0) 2017.12.18
RGB To Hex Conversion ( 5 kyu )  (0) 2017.12.11
Checking Groups ( 6 kyu )  (0) 2017.12.11

Simple Fun #290: Sum Of Threes ( 6 kyu )

문제

Task

Given a number n, return a string representing it as a sum of distinct powers of three, or return “Impossible” if that’s not possible to achieve.

Input/Output

[input] integer n

A positive integer n.

1 ≤ n ≤ 10^16.

[output] a string

A string representing the sum of powers of three which adds up to n, or “Impossible” if there is no solution. If the solution does exist, it should be return as “3a1+3a2+ … +3^an”, where ai for 0 ≤ i ≤ n represents the corresponding exponent of the term. The terms in the string should also be sorted in descending order, meaning that higher powers should appear before the lower ones in the string (“30+31” is incorrect, whereas “31+30” is correct).

인자로 주어진 수가 3의 제곱수의 합으로 나타내질 수 있는지를 판별하는 문제

풀이

function sumOfThrees(n) {
  let str = n.toString(3), result = '';
  if ( !(str.indexOf('2') === -1) ) return 'Impossible';
  for ( let i = 0; i < str.length; i++ ) {
    if ( str[i] === '1' ) {
      result += `3^${str.length-1-i}+`
    }
  }
  return result.slice(0, result.length-1);
}

3의 제곱수임을 판별하기 위해 3진법으로 변환 후에, 2가 있으면 impossible을 리턴하고 else 경우에 각 진법의 자릿수만큼 곱한 스트링을 결과값에 더해 리턴

다른 사람의 풀이

function sumOfThrees(n) {
  var t = n.toString(3)
  return /2/.test(t) ? "Impossible"  : 
  [...t].reverse().reduce((a,v,k)=>
    (v==1) ? a.concat("3^"+k) : a, []).reverse().join('+')
}

접근은 같지만 깔끔한 풀이


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

String average ( 6 kyu )  (0) 2017.12.19
Array Helper ( 6 kyu )  (0) 2017.12.19
RGB To Hex Conversion ( 5 kyu )  (0) 2017.12.11
Checking Groups ( 6 kyu )  (0) 2017.12.11
Rectangle into Squares ( 6 kyu )  (0) 2017.12.11

RGB To Hex Conversion ( 5 kyu )

문제

The rgb() method is incomplete. Complete the method so that passing in RGB decimal values will result in a hexadecimal representation being returned. The valid decimal values for RGB are 0 - 255. Any (r,g,b) argument values that fall out of that range should be rounded to the closest valid value.

The following are examples of expected output values:

rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3

rgb를 16진법으로 변환하는 문제

풀이

function rgb(r, g, b){
  let arr = [r, g, b];
  let result = '';
  for ( let i = 0; i < 3; i++ ) {
    if ( arr[i] < 0 ) {
      result += '00';
    } else if ( arr[i] > 255 ) {
      result += 'FF';
    } else {
      if ( arr[i].toString(16).length < 2 ) {
        result += '0' + arr[i].toString(16);
      } else {
        result += arr[i].toString(16).toUpperCase();
      }
    }
  }
  return result
}

0~255 밖인 경우 예외처리를 하고

toString(16)으로 16진법으로 변환하는데 이때 숫자는 한자리로 나오기 때문에 앞에 0을 붙여주고 더해서 리턴

조건문이 많이걸려서 지저분하다

다른 사람의 풀이

function rgb(r, g, b){
  return toHex(r)+toHex(g)+toHex(b);
}

function toHex(d) {
    if(d < 0 ) {return "00";}
    if(d > 255 ) {return "FF";}
    return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()
}

slice를 뒤에서부터하는거 똑똑한 방법인것 같음!


+ Recent posts