입력 받기
백준에서 입력을 받으려면 `fs` 모듈을 사용해야 한다.
기본
const input = require("fs")
.readFileSync("/dev/stdin", "utf-8")
.toString()
.trim()
.split("\n")
행렬
`n`과 `m`을 입력받아 `n` x `m` 행렬을 입력 받는다.
const fs = require("fs");
const [[n, m], ...map] = fs
.readFileSync("/dev/stdin", "utf-8")
.trim()
.split("\n")
.map((line) => line.split(" ").map(Number));
문자열 조작
문자열을 배열로 변환
const arr = str.split("");
배열 조작
배열 선언 및 초기화
- 특정 길이의 빈 배열
const arr = new Array(5); // [ <5 empty items> ]
`undefined`조차 채워지지 않은 빈 배열을 만든다. `length` 속성만 5로 설정하고, 인덱스 자체는 생성하지 않는다.
- 일정한 타입의 값으로 초기화
const arr = Array(5).fill(0); // [0, 0, 0, 0, 0]
- 인덱스를 기반으로 초기화
const arr = Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]
- 2차원 배열 초기화
const arr = Array.from({ length: 5 }, () => Array(5).fill(0));
- `map` 메서드를 사용한 초기화
const arr = [...Array(5)].map((_, i) => i * 2); // [0, 2, 4, 6, 8]
특정 조건에 맞게 배열을 초기화하고 싶을 때 `map` 메서드로 초기화한다.
스프레드 연산자를 사용하는 이유는 `new Array(5)`와 같이 선언하면 인덱스가 존재하지 않아 `map` 메서드를 사용할 수 없기 때문이다.
배열 정렬
인자로 정렬 기준을 전달하지 않으면 문자열을 기준으로 정렬한다.
arr.sort((a, b) => a - b) // 오름차순
arr.sort((a, b) => b - a) // 내림차순
배열 모든 요소의 합
const sum = numbers.reduce((acc, cur) => acc + cur, 0);
배열 뒤집기
const answer = arr.slice().reverse();
배열에서 최댓값 찾기
const max = arr.reduce((acc, cur) => Math.max(acc, cur));
배열에서 중복 제거
const arr = [1, 2, 2, 3, 4];
const unique = [...new Set(arr)]; // [1, 2, 3 ,4]
배열을 문자열로 변환
const arr = [1, 2, 3]
arr.join("");
Set 객체 사용
Set의 프로퍼티, 메서드
- `add(value)`
- `has(value)`
- `delete(value)`
- `clear()`
- `size`
- `entries()`: `[value, value]` 쌍을 반환
- `keys()`
- `values()`
- `forEach(callback)`
Map 객체 사용
자바스크립트의 Map 객체는 모든 타입을 키 또는 값으로 저장할 수 있다.
자바스크립트의 Map 객체는 내부적으로 배열로 이루어져 있다.
때문에 엔트리를 반환하면 키-값 쌍의 배열의 배열이 반환된다.
const entries = [...map.entries()]; // [[1, 10], [2, 20]]
Map의 프로퍼티, 메서드
- `set(key, value)`
- `get(key)`
- `has(key)`
- `delete(key)`
- `clear()`
- `size`
- `entries()`
- `keys()`
- `values()`
- `forEach(callback)`
큐
클래스로 구현, 노드를 활용한 큐
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}
add(value) {
const newNode = new Node(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.size++;
}
poll() {
if (!this.head) return null;
const removeNode = this.head;
this.head = this.head.next;
if (!this.head) {
this.tail = null;
}
this.size--;
return removeNode.value;
}
}
생성자 함수를 활용한 큐
const Queue = () => {
const queue = [];
let head = 0;
let tail = 0;
return {
add: (e) => {
queue.push(e);
tail++;
},
poll: () => {
return queue[head++];
},
get length() {
return tail - head;
}
}
}
진수 변환
10진수를 N진수로 변환
const num = 10;
console.log(num.toString(2)); // 1010
N진수를 10진수로 변환
const num = 1010;
console.log(parseInt(num, 2));
기타
- 숫자가 정수인지 확인하는 메서드
Number.isInteger(int);
- 배열의 내용물을 기준으로 유일성을 보장하고 싶을 때
const unique = Array.from(new Set((arr.map(e => JSON.stringify(e))))).map(str => JSON.parse(str))
DFS/BFS
const input = require("fs")
.readFileSync(process.platform === "linux" ? "/dev/stdin" : "./input.txt", "utf-8")
.trim()
.split("\n");
const [n, m, v] = input[0].split(" ").map(Number);
const graph = Array.from({ length: n + 1 }, () => [])
for (let i = 1; i <= m; i++) {
const [from, to] = input[i].split(" ").map(Number);
graph[from].push(to);
graph[to].push(from);
}
for (let i = 1; i <= n; i++) {
graph[i].sort((a, b) => a - b);
}
const visitedDfs = Array(n + 1).fill(false);
const pathDfs = [];
function dfs(node) {
visitedDfs[node] = true;
pathDfs.push(node);
for (const next of graph[node]) {
if (!visitedDfs[next]) {
dfs(next);
}
}
}
dfs(v);
console.log(pathDfs.join(" "));
const visitedBfs = Array(n + 1).fill(false);
const pathBfs = [];
function bfs(node) {
const q = [node];
visitedBfs[node] = true;
while (q.length > 0) {
const next = q.shift();
pathBfs.push(next);
for (const to of graph[next]) {
if (!visitedBfs[to]) {
visitedBfs[to] = true;
q.push(to);
}
}
}
}
bfs(v);
console.log(pathBfs.join(" "));

'언어 > JavaScript' 카테고리의 다른 글
| [Web API] Intersection Observer API에 대해 간단히 알아보자. (feat. 무한 스크롤) (0) | 2025.12.01 |
|---|
