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를 뒤에서부터하는거 똑똑한 방법인것 같음!


Checking Groups ( 6 kyu )

문제

In English and programming, groups can be made using symbols such as () and {} that change meaning. However, these groups must be closed in the correct order to maintain correct syntax.

Your job in this kata will be to make a program that checks a string for correct grouping. For instance, the following groups are done correctly:

({})
[[]()]
[{()}]

The next are done incorrectly:

{(})
([]
[])

주어진 문자열이 괄호로 완벽하게 닫혀있는지 판별하는 문제

풀이

 function groupCheck(s){
   while ( s.indexOf('()') !== -1 || s.indexOf('{}') !== -1 || s.indexOf('[]') !== -1 ) {
     if ( s.indexOf('()') !== -1 ) {
       s = s.slice(0, s.indexOf('()')) + s.slice(s.indexOf('()')+2, s.length);
     } else if ( s.indexOf('{}') !== -1 ) {
       s = s.slice(0, s.indexOf('{}')) + s.slice(s.indexOf('{}')+2, s.length);
     } else if ( s.indexOf('[]') !== -1 ) {
       s = s.slice(0, s.indexOf('[]')) + s.slice(s.indexOf('[]')+2, s.length);
     }
   }
   return (s === '')
 }

(), {}, [] 가 없을 때 까지 문자열에서 삭제해 빈 문자열이 남으면 true, 아니면 false 리턴

다른 사람의 풀이

 function groupCheck(s){
   var r = /\{\}|\[\]|\(\)/;
   while(r.test(s))
     s = s.replace(r, '');  
   return !s.length;   
 }

풀이는 비슷한데 정규식을 멋있게 쓴 것 같음


Rectangle into Squares ( 6 kyu )

문제

The drawing below gives an idea of how to cut a given “true” rectangle into squares (“true” rectangle meaning that the two dimensions are different).

alternative text

Can you translate this drawing into an algorithm?

You will be given two dimensions

a positive integer length (parameter named lng)
a positive integer width (parameter named wdth)

You will return an array with the size of each of the squares.

Shell bash returns a string.

sqInRect(5, 3) should return [3, 2, 1, 1]
sqInRect(3, 5) should return [3, 2, 1, 1]

너비와 높이가 주어지면 안에 들어갈 수 있는 정사각형의 변의 길이를 배열로 담아 리턴

풀이

function sqInRect(lng, wdth){
  if ( lng === wdth ) return null;
  let result = [];
  while ( lng > 0 && wdth > 0 ) {
    if ( lng > wdth ) {
      result.push(wdth);
      lng = lng - wdth;
    } else {
      result.push(lng);
      wdth = wdth - lng
    }
  }
  return result;
}

lng, wdth중 큰 값에서 작은값을 빼면서 결과에 추가하는 방법으로 반복

다른 사람의 풀이

function sqInRect(lng, wdth){
  let arr = []
  if(lng === wdth) return null
  while(lng > 0 && wdth > 0){
    arr.push(lng > wdth ? wdth : lng)
    lng > wdth ? lng -= wdth : wdth -= lng
  }
  return arr
}

똑같이 풀었는데 삼항 연산자를 잘 사용한 풀이


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

RGB To Hex Conversion ( 5 kyu )  (0) 2017.12.11
Checking Groups ( 6 kyu )  (0) 2017.12.11
Does my number look big in this? ( 6 kyu )  (0) 2017.12.11
Triangle type ( 6 kyu )  (0) 2017.12.09
Pete, the baker ( 5 kyu )  (0) 2017.12.09

Does my number look big in this? ( 6 kyu )

문제

A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits.

For example, take 153 (3 digits):

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

and 1634 (4 digits):

1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634

Narcissistic Number를 판별하는 문제

풀이

function narcissistic( value ) {
  let str = value.toString(), len = str.length, sum = 0;
  for ( let i = 0; i < len; i++ ) {
    sum += Math.pow(str[i], len)
  }
  return sum === value ? true : false;
}

str에 문자열로 담아 각 자릿수를 len만큼 제곱해서 sum에 합쳐 value와 비교후 결과값 리턴

다른 사람의 풀이

function narcissistic( value ) {
  return ('' + value).split('').reduce(function(p, c){
    return p + Math.pow(c, ('' + value).length)
    }, 0) == value;
}

toString이 아니라 ‘’을 더해서 문자열로 만드는 방법은 신기하네


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

Checking Groups ( 6 kyu )  (0) 2017.12.11
Rectangle into Squares ( 6 kyu )  (0) 2017.12.11
Triangle type ( 6 kyu )  (0) 2017.12.09
Pete, the baker ( 5 kyu )  (0) 2017.12.09
Largest 5 digit number in a series ( 5 kyu )  (0) 2017.12.08

Triangle type ( 6 kyu )

문제

In this kata, you should calculate type of triangle with three given sides a, b and c (given in any order).

If all angles are less than 90°, this triangle is acute and function should return 1.

If one angle is strictly 90°, this triangle is right and function should return 2.

If one angle more than 90°, this triangle is obtuse and function should return 3.

If three sides cannot form triangle, or one angle is 180° (which turns triangle into segment) - function should return 0.

Input parameters are sides of given triangle. All input values are non-negative floating point or integer numbers (or both).

Examples:

triangleType(2, 4, 6); // return 0 (Not triangle)
triangleType(8, 5, 7); // return 1 (Acute, angles are approx. 82°, 38° and 60°)
triangleType(3, 4, 5); // return 2 (Right, angles are approx. 37°, 53° and exactly 90°)
triangleType(7, 12, 8); // return 3 (Obtuse, angles are approx. 34°, 106° and 40°)

삼각형이 되는지 여부와 된다면 어떤 삼각형인지 구하는 문제

풀이

function triangleType(a, b, c){
  let arr = [a, b, c].sort((a,b) => { return b-a });
  if ( arr[0] >= arr[1] + arr[2] ) return 0;
  if ( arr[0]*arr[0] < arr[1]*arr[1] + arr[2]*arr[2] ) {
    return 1
  } else if ( arr[0]*arr[0] === arr[1]*arr[1] + arr[2]*arr[2] ) {
    return 2 
  } else {
    return 3
  }  
}

삼각형이 되는지 가려낸 뒤에, 모양에 따라 if문으로 리턴

다른 사람의 풀이

똑같당


Pete, the baker ( 5 kyu )

문제

Pete likes to bake some cakes. He has some recipes and ingredients. Unfortunately he is not good in maths. Can you help him to find out, how many cakes he could bake considering his recipes?

Write a function cakes(), which takes the recipe (object) and the available ingredients (also an object) and returns the maximum number of cakes Pete can bake (integer). For simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200). Ingredients that are not present in the objects, can be considered as 0.

Examples:

// must return 2
cakes({flour: 500, sugar: 200, eggs: 1}, {flour: 1200, sugar: 1200, eggs: 5, milk: 200}); 
// must return 0
cakes({apples: 3, flour: 300, sugar: 150, milk: 100, oil: 100}, {sugar: 500, flour: 2000, milk: 2000});

만들 수 있는 완제품의 개수를 리턴하는 문제

풀이

function cakes(recipe, available) {
  let num = [];
  for ( let i in recipe ) {
    if ( available[i] === undefined ) return 0;
    num.push(parseInt(available[i]/recipe[i]))
  }
  num.sort((a,b) => { return a-b });
  return num[0];
}

이용가능한 재료에 레시피 내용이 없으면 0 리턴, 나머지는 재료마다 가능한 개수를 num에 담아 최솟값을 리턴

다른 사람의 풀이

function cakes(recipe, available) {
  return Object.keys(recipe).reduce(function(val, ingredient) {
    return Math.min(Math.floor(available[ingredient] / recipe[ingredient] || 0), val)
  }, Infinity)  
}

똑똑하게 잘푼 풀이.


Largest 5 digit number in a series ( 5 kyu )

문제

In the following 6 digit number:

283910

91 is the greatest sequence of 2 digits.

In the following 10 digit number:

1234567890

67890 is the greatest sequence of 5 digits.

Complete the solution so that it returns the largest five digit number found within the number given. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits.

주어진 숫자중 연속된 5자리로 이루어진 가장 큰 수를 찾는 문제

풀이

function solution(digits){
  let str = digits.toString();
  let max = Number(str.slice(0, 5));
  for ( let i = 0; i <= str.length-5; i++ ) {
    if ( Number(str.slice(i, i+5)) > max ) {
      max = Number(str.slice(i, i+5))
    }
  return max;
}

5개씩 잘라서 비교한 뒤에 가장 큰 값을 리턴

다른 사람의 풀이

function solution(digits){
  if (digits.length <= 5) return Number(digits);
  return Math.max(Number(digits.substr(0, 5)), solution(digits.substr(1)));
}

접근은 같지만 메소드로 조금 더 짧게 표현


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

Triangle type ( 6 kyu )  (0) 2017.12.09
Pete, the baker ( 5 kyu )  (0) 2017.12.09
Sort the odd ( 6 kyu )  (0) 2017.12.06
Is a number prime? ( 6 kyu )  (0) 2017.12.06
Create Phone Number ( 6 kyu )  (0) 2017.12.06

Sort the odd ( 6 kyu )

문제

You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.

Zero isn’t an odd number and you don’t need to move it. If you have an empty array, you need to return it.

Example

sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]

배열에서 홀수만 순서대로 정렬하는 문제

풀이

function sortArray(array) {
  let idx = [], odd = [], j = 0;
  for ( let i = 0; i < array.length; i++ ) {
    if ( array[i] % 2 === 1 ) {
      odd.push(array[i]);
      idx.push(i);
    }
  }
  odd.sort((a,b) => { return a-b });
  idx.sort((a,b) => { return a-b });
  for ( let i of idx ) {
    array[i] = odd[j];
    j++
  }
  return array
}

너무 복잡하게 풀었다..

array를 포문으로 돌면서 홀수와 해당 인덱스를 odd, idx에 담아 오름차순으로 정렬 후에 기본 배열 array에 정렬한 값을 대입하는 방법

다른 사람의 풀이

function sortArray(array) {
  const odd = array.filter((x) => x % 2).sort((a,b) => a - b);
  return array.map((x) => x % 2 ? odd.shift() : x);
}

맵, 필터 같이쓰면 풀수있겠다 생각은 했는데 이렇게 접근하면 풀 수 있구나 싶은 코드.

shift() 사용하기.. 메모..


+ Recent posts