Sorting on planet Twisted-3-7 ( 6 kyu )

문제

There is a planet… in a galaxy far far away. It is exactly like our planet, but it has one difference:

The values of the digits 3 and 7 are twisted. Our 3 means 7 on the planet Twisted-3-7. And 7 means 3.

Your task is to create a method, that can sort an array the way it would be sorted on Twisted-3-7.

7 Examples from a friend from Twisted-3-7:

[1,2,3,4,5,6,7,8,9] -> [1,2,7,4,5,6,3,8,9]
[12,13,14] -> [12,14,13]
[9,2,4,7,3] -> [2,7,4,3,9]

3과 7이 바뀌었다 가정하고 정렬하는 문제

풀이

function sortTwisted37(array) {
  function change(val) {
    let result = val.toString().split('');
    for ( let i = 0; i < result.length; i++ ) {
      if ( result[i] === '3' ) result[i] = '7';
      else if ( result[i] === '7' ) result[i] = '3';
    }
    return Number(result.join(''));
  }
  let arr = array.slice().map( a => change(a) );
  arr.sort((a,b) => a-b);
  return arr.map( a => change(a) )
}

3,7을 바꿔 정렬 후 다시 바꿔줌

다른 사람의 풀이

function sortTwisted37(array) {
  const MAPPING = {7:3,3:7};

  return array.slice().sort((a,b) => twist(a) - twist(b));

  function twist(number) {
    return parseInt(number.toString().replace(/[37]/g,a=>MAPPING[a]));
  }
}

replace로 동시에 처리하려는 방법을 생각했는데 이렇게 하는 방법이 있었다.

왕꿀팁


Integer depth ( 6 kyu )

문제

The depth of an integer n is defined to be how many multiples of n it is necessary to compute before all 10 digits have appeared at least once in some multiple.

example:

let see n=42

Multiple         value         digits     comment
42*1              42            2,4
42*2              84             8         4 existed
42*3              126           1,6        2 existed
42*4              168            -         all existed
42*5              210            0         2,1 existed
42*6              252            5         2 existed
42*7              294            9         2,4 existed
42*8              336            3         6 existed
42*9              378            7         3,8 existed

Looking at the above table under digits column you can find all the digits from 0 to 9, Hence it required 9 multiples of 42 to get all the digits. So the depth of 42 is 9. Write a function named computeDepth which computes the depth of its integer argument.Only positive numbers greater than zero will be passed as an input.

몇까지 곱했을 때 0부터 9까지 나오는지 구하는 문제

풀이

function computeDepth (x){
  let result = '', count =1
  while ( [...new Set(result)].length < 10 ) {
    result += x*count;
    count++;
  }
  return count-1;
}

Set을 이용해 중복을 제거해 length로 10이 될때까지 반복문을 돌며 count

다른 사람의 풀이

별로임


Simple reversed parenthesis ( 6 kyu )

문제

Given a string, return the minimal number of parenthesis reversals needed to make balanced parenthesis.

For example:

solve(")(") = 2 Because we need to reverse ")" to "(" and "(" to ")". These are 2 reversals.
solve("(((())") = 1 We need to reverse just one "(" parenthesis to make it balanced.
solve("(((") = -1 Not possible to form balanced parenthesis. Return -1.

괄호쌍을 맞추기 위해 최소 몇개의 괄호를 뒤집어야 하는지 구하는 문제

풀이

function solve(s) {
  while ( s.includes('()') ) {
    s = s.replace(/\(\)/g, '');
  }
  if ( s.length % 2 === 1 ) return -1;
  let count = 0;
  const obj = {
      ')(': 2,
      '((': 1,
      '))': 1,
    };
  for ( let i = 0; i <= s.length-2; i += 2 ) {
    count += obj[s[i]+s[i+1]]
  }
  return count;
}

맞는 괄호쌍이 없어질 때까지 while로 지워주고,

객체를 만들어 뒤집어야하는 개수를 미리 적어 놓고 찾아서 count에 더해줌

다른 사람의 풀이

function solve(s){
  if(s.length%2) return -1;
  var t=0, d=0;
  for(let c of s) {
    if(c==='(') d++;
    else if(d) d--;
    else {t++; d++;}
  }
  return t+d/2;
}

모르겠지만 신기하게 풀었다


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

+ Recent posts