Max Collatz Sequence Length ( 5 kyu )

문제

In this kata we will take a look at the length of collatz sequences. And how they evolve. Write a function that take a positive integer n and return the number between 1 and n that has the maximum Collatz sequence length and the maximum length. The output has to take the form of an array [number, maxLength] For exemple the Collatz sequence of 4 is [4,2,1], 3 is [3,10,5,16,8,4,2,1], 2 is [2,1], 1 is [1], so MaxCollatzLength(4) should return [3,8]. If n is not a positive integer, the function have to return [].

n 이하의 숫자중 콜라츠 순서를 적용해 가장 긴 길이를 리턴하는 문제

풀이

function MaxCollatzLength(n) {
  if ( n <= 0 || typeof n !== 'number' ) return [];
  let max = [1,1], temp, count;
  for ( let i = 2; i <= n; i++ ) {
    temp = i;
    count = 0;
    while ( temp > 1 ) {
      if ( temp % 2 === 0 ) temp = temp/2;
      else temp = temp*3 + 1;
      count++;
    }
    if ( count > max[1] ) max = [i, count+1]
  }
  return max;
}

temp에 n으로 시작해서 몇개의 콜라츠 순열이 나오는지 담고 연산 횟수를 count로 해서 최댓값을 리턴하는 방법

다른 사람의 풀이

별로임


Find the unique string ( 5 kyu )

문제

There is an array of strings. All strings contains similar letters except one. Try to find it!

findUniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) === 'BbBb'
findUniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) === 'foo'

Strings may contain spaces. Spaces is not significant, only non-spaces symbols matters. E.g. string that contains only spaces is like empty string.

It’s guaranteed that array contains more than 3 strings.

배열중 다른 알파벳으로 구성된 단어를 찾는 문제

풀이

function findUniq(arr) {
  let newArr = arr.map(a => { return [...new Set(a.toLowerCase())].sort().join('') });
  for ( let i = 0; i < newArr.length; i++ ) {
    if ( newArr.indexOf(newArr[i]) === newArr.lastIndexOf(newArr[i]) ) return arr[i]
  }
}

Set으로 중복을 제거 후에, indexOf로 유일한 값을 찾아 리턴

다른 사람의 풀이

별로임


Extract the domain name from a URL ( 5 kyu )

문제

Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:

domainName("http://github.com/carbonfive/raygun") == "github" 
domainName("http://www.zombie-bites.com") == "zombie-bites"
domainName("https://www.cnet.com") == "cnet"

도메인의 이름만 뽑아 리턴하는 문제

풀이

function domainName(url){
  let arr = url.split('.');
  if ( arr[0].includes('www') ) return arr[1];
  if ( !arr[0].includes('http') ) return arr[0];
  return arr[0].slice(arr[0].indexOf('//')+2, arr[0].length);
}

.을 기준으로 배열로 잘라 www가 있으면 1번 인덱스 리턴

http가 없으면 0번 인덱스 리턴

나머지는 //를 기준으로 잘라 리턴

다른 사람의 풀이

function domainName(url){
  return url.match(/(?:http(?:s)?:\/\/)?(?:w{3}\.)?([^\.]+)/i)[1];
}

정규식이 있을 것 같았는데 따라는 못하겠다


Throwing Darts ( 6 kyu )

문제

You’ve just recently been hired to calculate scores for a Dart Board game!

Scoring specifications:

0 points - radius above 10
5 points - radius between 5 and 10 inclusive
10 points - radius less than 5
If all radiuses are less than 5, award 100 BONUS POINTS!

Write a function that accepts an array of radiuses (can be integers and/or floats), and returns a total score using the above specification.

An empty array should return 0.

Examples:

scoreThrows( [1, 5, 11] )    =>  15
scoreThrows( [15, 20, 30] )  =>  0
scoreThrows( [1, 2, 3, 4] )  =>  140

다트 점수내기, 4발 던져서 1,2,3,4에 넣으면 100점추가

풀이

function scoreThrows(radiuses){
  let point = [], result = 0;
  for ( let i of radiuses ) {
    if ( i < 5 ) {
      result += 10;
      point.push(i)
    } else if ( i >=5 && i <= 10 ) {
      result += 5;
    }
  }
  if ( [...new Set(point)].length === 4 && radiuses.length === 4 ) result += 100
  return result;
}

케이스를 많이 나눠 생각했는데 테스트케이스가 얼마 없어서 의미가 없어짐

다른 사람의 풀이

function scoreThrows(a){
 var result = a.reduce(function(p,c){
   return p + (c <5 ? 10 : c > 10 ? 0 : 5);
 },0) ;
 return result/a.length===10?result+100:result;
}

간단하게 푼 풀이


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

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


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

Integer depth ( 6 kyu )  (0) 2018.01.10
Simple reversed parenthesis ( 6 kyu )  (0) 2018.01.09
Array Deep Count ( 6 kyu )  (0) 2017.12.27
Fibonacci, Tribonacci and friends ( 6 kyu )  (0) 2017.12.23
What is the growth? ( 6 kyu )  (0) 2017.12.22
Dashatize it ( 6 kyu )  (0) 2017.12.20

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
Fibonacci, Tribonacci and friends ( 6 kyu )  (0) 2017.12.23
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
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
Array Helper ( 6 kyu )  (0) 2017.12.19

+ Recent posts