728x90

✨ASCII Code를 string으로 반환해주는 helper method

💻Example Code

console.log( String.fromCharCode(97) );
console.log( String.fromCharCode(113) );
console.log( String.fromCharCode(65) );

실행 결과(ASCII Code 97은 'a', 113은 'q', 65는 'A'라는 것을 알 수 있다)

😋 ASCII Code를 활용하는 문제를 풀 때 간혹 필요할 수 있다. ASCII Code를 string으로 바꿔준다.
백준 알파벳 찾기(Find alphabet) 알고리즘 문제를 풀 때 사용했다.

ASCII Code

👉자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode

 

String.fromCharCode()

The static String.fromCharCode() method returns a string created from the specified sequence of UTF-16 code units.

developer.mozilla.org

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.pop()  (0) 2020.01.04
Array.prototype.unshift()  (0) 2020.01.04
Array.prototype.indexOf()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
String.charCodeAt()  (0) 2019.12.31
728x90

✨ 주어진 array에서 찾고자하는 element의 index를 반환, 없다면 -1을 반환하는 helper method
(index는 가장 먼저 발견된 element 기준으로 반환된다)

💻Example Code

const arr = 'gamgongsa';

console.log( arr.indexOf('a') );
console.log( arr.indexOf('g') );
console.log( arr.indexOf('z') );

실행 결과('a'의 index는 1, 'g'의 index는 0, 'z'는 없기 때문에 -1)

😋 긴 문자열이 주어지고, 여기서 내가 원하는 알파벳이 있는지 없는지를 확인하고자 할 때 쓰기 좋은 helper method
알파벳 찾기(Find alphabet) 알고리즘 문제를 풀 때 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

 

Array.prototype.indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.unshift()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
728x90

https://www.acmicpc.net/problem/10809

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/32a64dbe8893d8f448507bb4900a155eb54a5764

😢 C언어로 자주 알파벳 가지고 놀았었는데, 기억이 잘 나지 않아서 검색을 좀 했다.
JavaScript로 ASCII Code 다루는 방법을 익혀서 새로웠지만 재밌었다.

😊 Solution 1)
단순하게 한 번 풀어보고자, 모든 알파벳을 배열에 담고 비교해보았다. for ... of를 이용해서 알파벳을 하나씩 반복해주고,
if else를 이용해서 해당 알파벳이 있다면 index를, 없다면 -1를 배열로 저장하였다. 출력은 join(' ')으로 형식을 맞춰주면 된다.


Solution 2)
먼저, 결과값을 담아줄 result array를 선언하였다. 그리고
for loop의 범위로 a-z를 주었다. 'a'는 ASCII Code 97번이고, 'z'는 ASCII Code 122번이기 때문에 97-122까지 반복 실행된다.
입력된 문자열(input 변수)에 해당하는 알파벳이 있다면 그 값의 index를, 없다면 -1를 반환하여 result array에 저장한다.
마지막으로, join(' ')을 통해 출력 형식을 맞춰 주면 된다.

가장 중요한 것-1 또는 해당 index라는 키워드가 나왔을 때, indexOf를 떠올릴 수 있어야 한다.

✔ String.prototype.charCodeAt()

각 알파벳의 ASCII Code를 알아내기 위해 사용하였다.
JavaScript-helper method에서 예제를 다뤄 보겠다.

✔ String.fromCharCode()

해당 ASCII Code에 해당하는 문자를 반환한다.
indexOf안에 찾고자하는 character를 넣기 위해 사용했다.(a-z의 ASCII Code가 순서대로 들어간다)
JavaScript-helper method에서 예제를 다뤄 보겠다.

✔ String.prototype.indexOf()

입력받은 값중에 해당 알파벳이 있는지, 있다면 그 위치(index)를 반환받고, 없다면 -1을 반환받기 위해 사용하였다.
JavaScript-helper method에서 예제를 다뤄 보겠다.

Full Code

// 2nd Solution
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString();
 
const input = 'baekjoon';
const result = [];
 
for (let i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) {
result.push(input.indexOf(String.fromCharCode(i)));
}
 
console.log(result.join(' '));
 
// 1st Solution(not so good)
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// const input = ['baekjoon'];
// const checker = [
// 'a',
// 'b',
// 'c',
// 'd',
// 'e',
// 'f',
// 'g',
// 'h',
// 'i',
// 'j',
// 'k',
// 'l',
// 'm',
// 'n',
// 'o',
// 'p',
// 'q',
// 'r',
// 's',
// 't',
// 'u',
// 'v',
// 'w',
// 'x',
// 'y',
// 'z'
// ];
 
// const result = [];
 
// for (let char of checker) {
// if (input[0].includes(char)) {
// result.push(input[0].indexOf(char));
// } else {
// result.push(-1);
// }
// }
 
// console.log(result.join(' '));

+ Recent posts