Your order, please ( 6 kyu )

문제

Your task is to sort a given string. Each word in the String will contain a single number. This number is the position the word should have in the result.

Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

If the input String is empty, return an empty String. The words in the input String will only contain valid consecutive numbers.

For an input: “is2 Thi1s T4est 3a” the function should return “Thi1s is2 3a T4est”

your_order("is2 Thi1s T4est 3a")
[1] "Thi1s is2 3a T4est"

문자열에서 단어마다 숫자가 있는데 숫자 순서대로 나열하는 문제

풀이

function order(words){
  let arr = words.split(' ');
  let num = [];
  for ( let i = 0; i < arr.length; i++ ) {
    num[arr[i].match(/[1-9]/)] = arr[i]
  }
  num.shift();
  return num.join(' ');
}

단어마다 쪼개서 배열로 arr에 담고, num이라는 배열에 숫자 순서대로 담아 join으로 합쳐 리턴

다른 사람의 풀이

function order(words){

  return words.split(' ').sort(function(a, b){
      return a.match(/\d/) - b.match(/\d/);
   }).join(' ');
}

생각한 방법보다 훨씬 간단하게 접근

신박하군


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

Array.diff ( 6 kyu )  (0) 2017.11.30
Are they the "same"? ( 6 kyu )  (0) 2017.11.30
Greed is Good ( 5 kyu )  (0) 2017.11.30
Two Joggers ( 5 kyu )  (0) 2017.11.30
First non-repeating character ( 5 kyu )  (0) 2017.11.30

Greed is Good ( 5 kyu )

문제

Greed is a dice game played with five six-sided dice. Your mission, should you choose to accept it, is to score a throw according to these rules. You will always be given an array with five six-sided dice values.

 Three 1's => 1000 points
 Three 6's =>  600 points
 Three 5's =>  500 points
 Three 4's =>  400 points
 Three 3's =>  300 points
 Three 2's =>  200 points
 One   1   =>  100 points
 One   5   =>   50 point

A single die can only be counted once in each roll. For example, a “5” can only count as part of a triplet (contributing to the 500 points) or as a single 50 points, but not both in the same roll.

 Throw       Score
 ---------   ------------------
 5 1 3 4 1   50 + 2 * 100 = 250
 1 1 1 3 1   1000 + 100 = 1100
 2 4 4 5 4   400 + 50 = 450

다섯개의 주사위를 던져서 위에 있는 스코어판 대로 점수를 매겨 리턴

풀이

function score( dice ) {
  let result = 0;
  let three = { 1: 1000, 2: 200, 3: 300, 4: 400, 5: 500,6: 600 }
  let one = { 1: 100, 5: 50 };
  let obj = {};
  for ( let i = 0; i < 5; i++ ) {
    if ( obj[dice[i]] ) {
      obj[dice[i]]++;
    } else {
      obj[dice[i]] = 1;
    }
  }
  for ( let i in obj ) {
    if ( obj[i] >= 3 ) {
      result += three[i];
      obj[i] -= 3
    }
    if ( one[i] ) {
      result += one[i]*obj[i]
    }
  }
  return result;
}

three, one에 각각 점수를 객체로 담아놓고,

첫번째 포문에서 주사위의 값들을 obj에 담아 obj로 다시 포문을 돌려 one과 three를 사용해 점수를 추가 후 리턴

다른 사람의 풀이

function score( dice ) {
  var dc = [0,0,0,0,0,0];
  var tdr = [1000,200,300,400,500,600];
  var sdr = [100,0,0,0,50,0];
  dice.forEach(function(x){ dc[x-1]++; });
  return dc.reduce(function(s,x,i){ 
    return s + (x >= 3? tdr[i] : 0) + sdr[i]*(x % 3);
  },0);
}

배열로만 인덱스를 구성해 이중포문으로 구성

코드는 별로 좋은것 같지는 않지만 모양이 예뻐서 가져옴.


Two Joggers ( 5 kyu )

문제

Your job is to complete the function nbrOfLaps(x, y) that, given the length of the laps for Bob and Charles, finds the number of laps that each jogger has to complete before they meet each other again, at the same time, at the start.

The function takes two arguments:

  1. The length of Bob’s lap (larger than 0)
  2. The length of Charles’ lap (larger than 0)

The function should return an array (Tuple in C#) containing exactly two numbers:

  1. The first number is the number of laps that Bob has to run
  2. The second number is the number of laps that Charles has to run

Examples:

nbrOfLaps(5, 3); // returns [3, 5]
nbrOfLaps(4, 6); // returns [3, 2

두 명이 서로 다른 원형 트랙을 돌면서 시작점에서 다시 만날때까지 몇바퀴를 돌아야 하는지 찾는 문제

풀이

var nbrOfLaps = function (x, y) {
  let gcd = 1;
  for ( let i = 2; i <= Math.min(x,y); i++ ) {
    if ( x % i === 0 && y % i === 0 ) {
      gcd = i;
    }
  }
  return [y/gcd, x/gcd];
}

gcd 즉 최대 공약수를 구하는 문제

약간의 연산을 더해 결과값 리턴

다른 사람의 풀이

function gcd(a, b) {
  if(b == 0)
    return a;
  return gcd(b, a % b);
}

var nbrOfLaps = function (x, y) {
  var lcm = (x*y)/ gcd(x,y);
  return [lcm/x, lcm/y];
}

유클리드 호제법 사용.

내가 짠 코드보다 훨씬 실행시간이 줄어들음


First non-repeating character ( 5 kyu )

문제

Write a function named firstNonRepeatingLetter† that takes a string input, and returns the first character that is not repeated anywhere in the string.

For example, if given the input ‘stress’, the function should return ‘t’, since the letter t only occurs once in the string, and occurs first in the string.

As an added challenge, upper- and lowercase letters are considered the same character, but the function should return the correct case for the initial letter. For example, the input ‘sTreSS’ should return ‘T’.

If a string contains all repeating characters, it should return the empty string (“”).

문자열중에 중복되지 않는 첫번째 알파벳을 리턴하는 문제,

대소문자를 구별하지 않음

풀이

function firstNonRepeatingLetter(s) {
  let low = s.toLowerCase();
  for ( let i = 0; i < s.length; i++ ) {
    if ( low.indexOf(low[i]) === low.lastIndexOf(low[i]) ) {
      return s[i]
    }
  }
  return '';
}

문자열을 소문자로 바꾼 뒤에 포문을 돌며 indexOf와 lastIndexOf를 비교해 둘의 인덱스가 같다면 해당 문자를 리턴

다른 사람의 풀이

function firstNonRepeatingLetter(s) {
  for(var i in s) {
    if(s.match(new RegExp(s[i],"gi")).length === 1) {
      return s[i];
    }
  }
  return '';
}

대소문자를 구별하지 않는 문제에서는 정규식을 사용할 줄 알면 좋을 것 같다.


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

Greed is Good ( 5 kyu )  (0) 2017.11.30
Two Joggers ( 5 kyu )  (0) 2017.11.30
Perimeter of squares in a rectangle ( 5 kyu )  (0) 2017.11.29
Palindrome chain length ( 5 kyu )  (0) 2017.11.29
Tribonacci Sequence ( 6 kyu )  (0) 2017.11.28

Perimeter of squares in a rectangle ( 5 kyu )

문제

The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It’s easy to see that the sum of the perimeters of these squares is : 4 (1 + 1 + 2 + 3 + 5 + 8) = 4 20 = 80

The function perimeter has for parameter n where n + 1 is the number of squares (they are numbered from 0 to n) and returns the total perimeter of all the squares.

perimeter(5)  should return 80
perimeter(7)  should return 216

정사각형을 이어붙힌 뒤에 둘레를 구하는 문제

피보나치 수열을 이용하라고 쓰여있음.

풀이

function perimeter(n) {
  let arr = [1,1];
  for ( let i = 2; i <= n; i++ ) {
    arr[i] = arr[i-1] + arr[i-2];
  }
  return 4*arr.reduce((a,b) => { return a+b });
}

원소의 개수가 n개인 피보나치 수열을 만든 뒤 합을 구한 뒤 4를 곱해서 리턴

다른 사람의 풀이

똑같넴


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

Two Joggers ( 5 kyu )  (0) 2017.11.30
First non-repeating character ( 5 kyu )  (0) 2017.11.30
Palindrome chain length ( 5 kyu )  (0) 2017.11.29
Tribonacci Sequence ( 6 kyu )  (0) 2017.11.28
Valid Braces ( 4 kyu )  (0) 2017.11.27

Palindrome chain length ( 5 kyu )

문제

Number is a palindrome if it is equal to the number with digits in reversed order. For example, 5, 44, 171, 4884 are palindromes and 43, 194, 4773 are not palindromes.

Write a method palindrome_chain_length which takes a positive number and returns the number of special steps needed to obtain a palindrome. The special step is: “reverse the digits, and add to the original number”. If the resulting number is not a palindrome, repeat the procedure with the sum until the resulting number is a palindrome.

If the input number is already a palindrome, the number of steps is 0.

Input will always be a positive integer.

For example, start with 87:

87 + 78 = 165; 165 + 561 = 726; 726 + 627 = 1353; 1353 + 3531 = 4884

4884 is a palindrome and we needed 4 steps to obtain it, so palindrome_chain_length(87) == 4

해당 숫자와 뒤집은 수의 합이 팰린드롬수가 될 때까지 몇번의 연산을 해야하는지 구하는 문제

풀이

var palindromeChainLength = function(n) {
  let count = 0;
  while ( n.toString() !== n.toString().split('').reverse().join('') ) {
    n = n + parseInt(n.toString().split('').reverse().join(''))
    count++
  }
  return count;
};

그냥 n이 팰린드롬 수가 될 때까지 횟수 반복, 카운트

왜 5 kyu 인가..

다른 사람의 풀이

var palindromeChainLength  = function(n) {  
  var x = parseInt( (""+n).split('').reverse().join('') );
  if(n != x){
    return 1 + palindromeChainLength (n + x);
  }
  return 0;
};

재귀로 푸는 방법


Tribonacci Sequence ( 6 kyu )

문제

Well met with Fibonacci bigger brother, AKA Tribonacci.

As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won’t get to hear non-native Italian speakers trying to pronounce it :(

So, if we are to start our Tribonacci sequence with [1, 1, 1] as a starting input (AKA signature), we have this sequence:

[1, 1 ,1, 3, 5, 9, 17, 31, ...]

문제가 더 있지만 생략

그냥 피보나치와 비슷하게 이전 세개의 합을 배열에 추가하는 문제

풀이

function tribonacci(signature,n){
  let result = signature;
  if ( n < 3 ) return result.slice(0,n);
  for ( let i = 3; i < n; i++ ) {
    result[i] = result[i-3] + result[i-2] + result[i-1];
  }
  return result;
}

그냥 결과를 담는 배열에 n이 3보다 작은경우 예외처리를 하고, 나머지는 배열에 원소를 추가해 리턴

다른 사람의 풀이

function tribonacci(s,n){
  var arr = [];
  for(var i=0; i<n; i++) {
    arr.push((i<3) ? s[i] : arr[i-1]+arr[i-2]+arr[i-3]);
  }
  return arr;
}

포문안에 삼항연산자로 예외처리, 방법은 같다.


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

Perimeter of squares in a rectangle ( 5 kyu )  (0) 2017.11.29
Palindrome chain length ( 5 kyu )  (0) 2017.11.29
Valid Braces ( 4 kyu )  (0) 2017.11.27
Who likes it? ( 6 kyu )  (0) 2017.11.27
Unique In Order ( 6 kyu )  (0) 2017.11.26

Valid Braces ( 4 kyu )

문제

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

This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}. Thanks to @arnedag for the idea!

All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.

What is considered Valid?

A string of braces is considered valid if all braces are matched with the correct brace.

Examples

"(){}[]"   =>  True
"([{}])"   =>  True
"(}"       =>  False
"[(])"     =>  False
"[({})](]" =>  False

괄호가 순서쌍이 맞게 이루어졌으면 true, 아니면 false 리턴

풀이

function validBraces(braces){
  while ( braces.indexOf("()") !== -1 || braces.indexOf("{}") !== -1 || braces.indexOf("[]") !== -1 ) {
    if ( braces.indexOf("()") !== -1 ) {
      braces = braces.slice(0, braces.indexOf("()")).concat(braces.slice(braces.indexOf("()")+2, braces.length))
    } else if ( braces.indexOf("{}") !== -1 ) {
      braces = braces.slice(0, braces.indexOf("{}")).concat(braces.slice(braces.indexOf("{}")+2, braces.length))
    } else if ( braces.indexOf("[]") !== -1 ) {
      braces = braces.slice(0, braces.indexOf("[]")).concat(braces.slice(braces.indexOf("[]")+2, braces.length))
    } 
  }
  return braces.length === 0 ? true : false;
}

while에 indexOf로 괄호쌍을 지워가면서 문자열이 전부 삭제되면 true 리턴, 아니라면 false 리턴

다른 사람의 풀이

function validBraces(braces){
 while(/\(\)|\[\]|\{\}/g.test(braces)){braces = braces.replace(/\(\)|\[\]|\{\}/g,"")}
 return !braces.length;
}

뭔진모르지만 고수느낌


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

Palindrome chain length ( 5 kyu )  (0) 2017.11.29
Tribonacci Sequence ( 6 kyu )  (0) 2017.11.28
Who likes it? ( 6 kyu )  (0) 2017.11.27
Unique In Order ( 6 kyu )  (0) 2017.11.26
Counting Duplicates ( 6 kyu )  (0) 2017.11.26

+ Recent posts