문제
10809번: 알파벳 찾기
각각의 알파벳에 대해서, a가 처음 등장하는 위치, b가 처음 등장하는 위치, ... z가 처음 등장하는 위치를 공백으로 구분해서 출력한다. 만약, 어떤 알파벳이 단어에 포함되어 있지 않다면 -1을 출
www.acmicpc.net
메모
- Array.prototype.push(): 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환한다.
- Array.prototype.indexOf(): 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.
- String.fromCharCode(): UTF-16 코드 유닛의 시퀀스로부터 문자열을 생성해 반환한다.
- Array.prototype.join(): 배열의 모든 요소를 연결해 하나의 문자열로 만든다.
정답
// 알파벳 배열을 따로 만들어서 찾기
let fs = require("fs");
let filePath = process.platform === "linux" ? "/dev/stdin" : "test.txt";
let str = fs.readFileSync(filePath).toString().split("");
let alphabet = Array(26)
.fill(0)
.map((_, x) => String.fromCharCode(x + 97));
let answer = [];
alphabet.map(x => {
if (str.includes(x)) {
answer.push(str.indexOf(x));
} else {
answer.push(-1);
}
});
console.log(answer.join(" "));
// 아스키 코드에서 찾기
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "test.txt";
const input = fs.readFileSync(filePath).toString().trim();
const answer = [];
for (i = 97; i <= 122; i++) {
answer.push(input.indexOf(String.fromCharCode(i)));
}
console.log(answer.join(" "));