본문 바로가기
알고리즘/Codewars

[Codewars] Replace With Alphabet Position (6 kyu) / JavaScript

by fluss 2022. 10. 30.

https://www.codewars.com/kata/546f922b54af40e1e90001da

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Welcome.

In this kata you are required to, given a string, replace every letter with its position in the alphabet.

If anything in the text isn't a letter, ignore it and don't return it.

"a" = 1, "b" = 2, etc.

 

Example

alphabetPosition("The sunset sets at twelve o' clock.")

Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" ( as a string )

 

설명:

환영합니다.

이 카타에서는 주어진 문자열에서 모든 글자를 알파벳의 위치를 바꿔야 합니다.

만약 글에 문자가 포함되어있지 않다면 무시하고 반환하지 마세요.

"a" = 1, "b" = 2, 등.

 

예시

alphabetPosition("The sunset sets at twelve o' clock.")

"20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"을 반환해야 합니다 (문자열로)

 

풀이

문자열을 모두 대문자로 바꾸고 주어진 문자의 유니코드 값을 이용해 대문자의 범위인 65부터 90(A에서 Z)이면 64를 빼서 배열에 저장하고 출력하였다.

 

코드

function alphabetPosition(text) {
  text = text.toUpperCase();
  let result = [];
  for(let i = 0; i < text.length; i++){
    let num = text.charCodeAt(i);
    if(num >= 65 && num <= 90){
      result.push(num - 64);
    }
  }
  return result.join(' ')
}

 

참고

https://ko.wikipedia.org/wiki/ASCII

 

ASCII - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. 1972 프린터 사용 설명서에 개시된 아스키 코드 차트표 미국정보교환표준부호(영어: American Standard Code for Information Interchange), 또는 줄여서 ASCII( , 아스키)는 영문

ko.wikipedia.org

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt

 

String.prototype.charCodeAt() - JavaScript | MDN

charCodeAt() 메서드는 주어진 인덱스에 대한 UTF-16 코드를 나타내는 0부터 65535 사이의 정수를 반환합니다.

developer.mozilla.org

 

댓글