문제
알파벳 소문자로만 이루어진 단어 S가 주어진다. 각각의 알파벳에 대해서, 단어에 포함되어 있는 경우에는 처음 등장하는 위치를, 포함되어 있지 않은 경우에는 -1을 출력하는 프로그램을 작성하시오.
첫째 줄에 단어 S가 주어진다. 단어의 길이는 100을 넘지 않으며, 알파벳 소문자로만 이루어져 있다.
해당 문제를 풀기 위해서는 유니코드 개념이 필요했다.
String.froCharCode() 메서드 기본 사용법
String.fromCharCode(65); // "A"
String.fromCharCode(65, 66, 67); // "ABC"
let str = '';
for (let i = 97; i <= 122; i++) {
console.log(String.fromCharCode(i));
str += String.fromCharCode(i);
}
// abcdefghijklmnopqrstuvwxyz
console.log(str);
식으로 출력할 수 있었다.
그렇지만 알고리즘을 처리할 때 직접 저렇게 하는 것보다는
미리 선언을 해줘서 하는 것이 더 빠르게 돌아갈 것이라고 생각했다.
Array.prototype.fill 메서드를 사용하면 전달받은 인수로 배열을 채울 수 있다.
const a = new Array(5).fill(0); // [0, 0, 0, 0, 0]
const b = [1, 2, 3, 4, 5].fill(0); // [0, 0, 0, 0, 0]
그래서 알파벳 수 만큼 미리 배열을 생성하고,
알파벳의 인덱스를 구해서 글자의 위치만큼 인덱스값을 할당해주면 안될까?
겹치는 값에 대해선 if문으로 방지하면 될 것 같았다.
var input = require("fs")
.readFileSync("20230307/example.txt")
.toString()
.split("\n");
let word = input[0].split("");
const alphabet = "abcdefghijklmnopqrstuvwxyz";
const checkArray = new Array(26).fill(-1);
for (let i = 0; i < word.length; i++) {
// i는 문자의 index값
// 알파벳은 몇번째 순서에 들어가야할지 알려준다.
if (checkArray[alphabet.indexOf(word[i])] === -1)
checkArray[alphabet.indexOf(word[i])] = i;
}
console.log(checkArray.join(" "));
레퍼런스
const input = require("fs").readFileSync("/dev/stdin").toString();
const result = [];
for (let i = 97; i <= 122; i++) {
result.push(input.indexOf(String.fromCharCode(i)));
}
console.log(result.join(" "));
퍼포먼스 비교를 하고 싶어서
Performance.now메소드를 활용하기로 하였다.
const t0 = performance.now()
const t1 = performance.now()
console.log(t1 - t0, 'milliseconds')
방법으로 구할 수 있다.
https://yceffort.kr/2020/12/measuring-performance-of-javascript-functions#performancenow
퍼포먼스가 여러번 할 때마다 변하지만 평균적으로 나온 시간을 적었다.
0.003초 차이가 나서 아쉬웠다.
https://mine-it-record.tistory.com/489
https://gurtn.tistory.com/76