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

Who likes it? ( 6 kyu )

문제

You probably know the “like” system from Facebook and other pages. People can “like” blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"

배열의 사람 수에따라 다른 문자열을 출력하는 문제

풀이

function likes(names) {
  switch ( names.length ) {
    case 0: return 'no one likes this';
    case 1: return `${names[0]} likes this`;
    case 2: return `${names[0]} and ${names[1]} like this`;
    case 3: return `${names[0]}, ${names[1]} and ${names[2]} like this`;
    default: return `${names[0]}, ${names[1]} and ${names.length-2} others like this`;
  }
}

코드워즈를 풀면서 처음으로 스위치 케이스를 사용함.

어려운 문젠 아닌듯

다른 사람의 풀이

똑같이 풀어서 안가져옴


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

Tribonacci Sequence ( 6 kyu )  (0) 2017.11.28
Valid Braces ( 4 kyu )  (0) 2017.11.27
Unique In Order ( 6 kyu )  (0) 2017.11.26
Counting Duplicates ( 6 kyu )  (0) 2017.11.26
Vasya - Clerk ( 6 kyu )  (0) 2017.11.26

Unique In Order ( 6 kyu )

문제

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

For example:

uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
uniqueInOrder('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
uniqueInOrder([1,2,2,3,3])       == [1,2,3]

문자열에서 연속으로 중복되는 단어를 제거해 배열로 리턴하는 문제

풀이

var uniqueInOrder=function(iterable){
  if ( !iterable ) return [];
  let temp = iterable[0], result = [];
  for ( let i = 1; i < iterable.length; i++ ) {
    if ( iterable[i] !== temp ) {
      result.push(temp);
      temp = iterable[i];
    }
  }
  result.push(iterable[iterable.length-1])
  return result;
}

가장 윗줄은 빈 배열일 때 예외처리

temp에 문자가 바뀌면 등록해놓고 새로운 문자로 바뀔때마다 result배열에 푸시, 마지막 인덱스 푸시 후 리턴

다른 사람의 풀이

function uniqueInOrder(it) {
  var result = []
  var last

  for (var i = 0; i < it.length; i++) {
    if (it[i] !== last) {
      result.push(last = it[i])
    }
  }

  return result
}

비슷한데 뭔가 다름

배열에 푸시하는 방식이 새로움


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

Valid Braces ( 4 kyu )  (0) 2017.11.27
Who likes it? ( 6 kyu )  (0) 2017.11.27
Counting Duplicates ( 6 kyu )  (0) 2017.11.26
Vasya - Clerk ( 6 kyu )  (0) 2017.11.26
Build a pile of Cubes ( 6 kyu )  (0) 2017.11.25

Counting Duplicates ( 6 kyu )

문제

Count the number of Duplicates

Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

Example

"abcde" -> 0 # no characters repeats more than once
"aabbcde" -> 2 # 'a' and 'b'
"aabBcde" -> 2 # 'a' occurs twice and 'b' twice (bandB)
"indivisibility" -> 1 # 'i' occurs six times
"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
"aA11" -> 2 # 'a' and '1'
"ABBA" -> 2 # 'A' and 'B' each occur twice

중복되는 단어의 개수를 리턴하는 간단한 문제

풀이

function duplicateCount(text){
  let obj = {}, count = 0;
  text = text.toLowerCase();
  for ( let i = 0; i < text.length; i++ ) {
    if ( obj[text[i]] ) {
      obj[text[i]]++;
    } else {
      obj[text[i]] = 1;
    }
  }
  for ( let j in obj ) {
    if ( obj[j] > 1 ) count++
  }
  return count;
}

obj에 단어 개수를 담아놓고, 1보다 크면 count를 하나씩 추가해서 리턴

다른 사람의 풀이

function duplicateCount(text){
  return (text.toLowerCase().split('').sort().join('').match(/([^])\1+/g) || []).length;
}

한 줄로 푸는게 역시 제일 멋있어


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

Who likes it? ( 6 kyu )  (0) 2017.11.27
Unique In Order ( 6 kyu )  (0) 2017.11.26
Vasya - Clerk ( 6 kyu )  (0) 2017.11.26
Build a pile of Cubes ( 6 kyu )  (0) 2017.11.25
Take a Ten Minute Walk ( 6 kyu )  (0) 2017.11.24

+ Recent posts