목차
NodeJs 입력 받기
보통 이런식으로 입력을 받는다.
const input = require("fs")
.readFileSync("./dev/stdin", "utf-8")
.trim()
.split("\n");
백준 입출력 팁
아래와 같이 dev폴더안에 stdin을 만들어서 쓰자 제출할때 매우 편하다.
출력 방법
출력시 console.log로 간편하게 할 수 있지만 줄바꿈이 자동으로 된다는 문제점이 있다.
그럴때는 아래 코드를 통해 해결할 수 있다. 문자열만 가능하기 때문에 String으로 바꾸는 것 잊지말자!
process.stdout.write(String(combinations[i][j])); //String만됨
입력 받은 배열 원하는 대로 조작하기
보통 위에 처럼 입력 받게 되면 한 배열의 원소가 이렇게 생기게 된다.
이것을 줄바꿈을 제거하고 숫자로 바꾸어 배열에 넣어보자
"1 2 3 4 5 \r"
아래와 같이 trim을 통해 공백이나 줄바꿈을 제거해주고 spliet으로 배열을 만들어 준 후
map을 통해 숫자로 바꾸어 주었다.
let arr = input[i].trim().split(" ").map(Number);
//1 2 3 4 5
인접 리스트와 이차원 배열 구현하기
//인접 리스트
let adjacency_list = Array.from({length: 5}, ()=>[])
//이차원 배열
let two_dimensional_array = Array.from(Array(5), ()=> Array(5))
정렬할 때 주의점
콘솔에서는 sort만 써도 정렬이 되지만 백준에서 제출하면 틀린다..
vector[i].sort((a,b)=> a-b);
해쉬맵 사용하기
아래와 같이 쓰면 key값이 같은 것들을 모아서 넣을 수 있다.
let fmap = new Map();
function addValueToMap(key, value) {
if (!fmap.has(key)) {
fmap.set(key, []);
}
fmap.get(key).push(value);
}
아래와 같이 순회할 수 있다.
for (let [key, value] of fmap) {
console.log(fmap.get(key));
}
큐 구현하기
굳이 shift로 큐를 간편하게 할 수 있는데 구현해야 할까라는 의문점이 들 수 있다.
바로 shift메서드는 배열을 활용한 큐이기 때문이다. 따라서 arr[0]을 제거해준 뒤
배열을 당겨주는 과정에서 O(N)이라는 시간 복잡도가 나온다..
(귀찮으면 왠만하면 시간 초과 안나니 shift쓰자..)
class Queue {
constructor() {
this.storage = new Map();
this.front = 0;
this.rear = 0;
}
size() {
return this.storage.size;
}
add(value) {
this.storage.set(this.rear, value);
this.rear += 1;
}
pop() {
if (this.size() === 0) return undefined; // 큐가 비어 있으면 undefined 반환
const item = this.storage.get(this.front);
this.storage.delete(this.front);
this.front += 1;
if (this.size() === 0) { // 마지막 요소가 삭제되면 초기화
this.front = 0;
this.rear = 0;
}
return item;
}
}
우선 순위 큐 구현
사실 이거때문에 NodeJs로 코테보기가 꺼려진다.. 왜 메서드 자체 제공안하는데ㅜ
그냥 우선순위큐 써야 되면 C++로 선택적 언어하자..
class MinHeap {
arr = [];
parent = idx => Math.floor((idx - 1) / 2);
left = idx => idx * 2 + 1;
right = idx => idx * 2 + 2;
last = () => this.arr.length - 1;
swap = (a, b) => ([this.arr[a], this.arr[b]] = [this.arr[b], this.arr[a]]);
isEmpty = () => this.arr.length === 0;
push(data) {
this.arr.push(data);
let now = 0;
while (now > 0 && this.arr[now][1] < this.arr[this.parent(now)][1]) {
const parent = this.parent(now);
this.swap(now, parent);
now = parent;
}
}
pop() {
this.swap(0, this.last());
const result = this.arr.pop();
let [now, left, right] = [0, 1, 2];
while (left <= this.last()) {
let change = left;
if (right <= this.last() && this.arr[right][1] < this.arr[left][1]) {
change = right;
}
if (this.arr[change][1] < this.arr[now][1]) {
this.swap(change, now);
now = change;
left = this.left(now);
right = this.right(now);
} else break;
}
return result;
}
}
간단한 bfs, dfs 구현
function bfs(start) {
queue.push(start);
visit[start] = 1;
while (queue.length) {
let cur = queue.shift();
process.stdout.write(`${String(cur)} `);
for (let i = 0; i < vector[cur].length; i++) {
if (visit[vector[cur][i]]) continue;
queue.push(vector[cur][i]);
visit[vector[cur][i]] = 1;
}
}
}
function dfs(cur) {
process.stdout.write(`${String(cur)} `);
visit[cur] = 1;
for (let i = 0; i < vector[cur].length; i++) {
if (!visit[vector[cur][i]]) {
dfs(vector[cur][i]);
}
}
}
코테 준비하면서 차후 추가 예정..
'코딩 정보' 카테고리의 다른 글
SSR vs CSR 정확히 이해하자 (0) | 2025.03.08 |
---|---|
깃허브 브랜치 전략에 대해 알아보자 (2) | 2024.11.21 |
백엔드와 함께 프론트 개발 시 유용한 패키지들 (0) | 2024.08.22 |
깃허브 브랜치를 잘못 merge했을 때 해결방안.. (2) | 2024.05.12 |
NodeJS를 위한 간략 개념 정리 (0) | 2024.04.01 |