const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on('line', function (line) {
console.log(line);
rl.close();
}).on('close', function () {
process.exit();
});
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let data = []; // 한 줄만 입력 받으면 배열로 정의할 필요는 없음
rl.on('line', function (line) {
if (!line) rl.close(); // 입력 없으면 입력 받기 종료
else data.push(line);
}).on('close', function () {
/* 문제 풀이 함수 실행 - 입력 받은 데이터 전달 */
console.log(solution(data));
process.exit();
});
/* 입력 받은 값으로 문제 풀이 실행하는 함수 */
function solution(data) {
/* 문제 풀이 로직 작성 및 answer에 반환할 값 저장 */
return answer;
}
정의해둔 data 배열에 입력으로 받은 값이 각 라인 별로 저장되어있다. 이를 solution 함수로 전달해 사용하면 된다.
2\n1 2\n3 4\n
와 같이 입력이 들어온다면, 입력은 3번 받게되고 다음 줄은 없기 때문에 자동으로 if (!line)에서 종료된다.['2', '1 2', '3 4']
로 저장된다.const readline = require('readline');
(async () => {
let rl = readline.createInterface({ input: process.stdin });
for await (const line of rl) {
console.log(line);
rl.close();
}
process.exit();
})();
const readline = require('readline');
(async () => {
let rl = readline.createInterface({ input: process.stdin });
let data = [];
for await (const line of rl) {
if (!line) rl.close(); // 입력 없으면 입력 받기 종료
else data.push(line);
}
rl.close();
/* 문제 풀이 함수 실행 - 입력 받은 데이터 전달 */
console.log(solution(data));
process.exit();
})();
/* 입력 받은 값으로 문제 풀이 실행하는 함수 */
function solution(data) {
/* 문제 풀이 로직 작성 및 answer에 반환할 값 저장 */
return answer;
}
재선언, 재할당
이 가능한 변수불가능
한 변수재할당 가능
한 변수함수 내에서 선언된 변수는 함수 내에서만 유효하고, 함수 외부에서는 참조할 수 없다.
var
변수는 함수 내에서만 유효하다.
function {}, if {}, for {}, while {}, try/catch {} 등의 모든 블록 내부에서 선언된 변수는 코드 블록 내에서만 유효하고, 코드 블록 외부에서는 참조할 수 없다.
const
,let
변수는 블록 내부에서만 유효하다. 만약 if 문 내에서 선언하면 if 블록 바깥에서는 참조할 수 없다.
let array = [];
let array = new Array();
new Array(n)
으로 적어주면 n 크기의 배열이 생성된다.
배열을 생성하고 값도 할당해줄 수 있다.
let array = Array.from({length: n}, (_, i) => 0);
위 예시는 배열 크기가 n이고 모든 배열의 값을 0으로 설정한다. 그러나 (_, i) => i로 설정하면 배열에 각 인덱스 값이 설정된다.
let array = Array.from(Array(n), () => Array(m).fill(0))
n*m 사이즈의 이차원 배열을 생성하고 0으로 채워준다.
let array = ['apple', 'banana', 'pineapple', 'mango'];
array.splice(2, 1); // array = ['apple', 'banana', 'mango']
let array = ['2', '3', '10'];
array.map(Number); // array = [2, 3, 10]
let array = [1, 2, 3, 4, 5, 6, 7, 8];
array.slice(0, 3); // [1, 2, 3];
slice(n, m)
을 사용하면 n번째 인덱스부터 m-1까지의 배열을 반환한다.
let string_array = ['a', 'c', 'b'];
string_array.sort(); // ['a', 'b', 'c']
let string_array = ['a', 'c', 'b'];
string_array.sort((a, b) => a > b ? -1 : 1); // ['c', 'b', 'a']
let number_array = [5, 2, 4];
number_array.sort((a, b) => a - b); // [2, 4, 5]
let number_array = [5, 2, 4];
number_array.sort((a, b) => b - a); // [5, 4, 2]
let number_array = [[2, 3], [4, 5], [0, 1]];
number_array.sort((a, b) => a[0] - b[0]); // [[0, 1], [2, 3], [4, 5]]
let number_array = [[2, 10], [2, 5], [0, 1]];
number_array.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]) // [[0, 1], [2, 5], [2, 10]]
첫번째 요소가 같다면 두번째 요소를 기준으로 오름차순 정렬하고, 그게 아니라면 첫번째 요소를 기준으로 오름차순 정렬한다.
for (let i = 0; i < 10; i++) {
console.log(i);
}
const information = { name: '짱구', age: 5, school: '떡잎유치원' };
for (const key in information) {
console.log(key); // name, age, school 순으로 출력
}
객체
를 반복할 때 쓰는 반복문이다.
const array = ['짱구', '유리', '철수', '맹구', '훈이'];
for (const item of array) {
console.log(item); // '짱구', '유리', '철수', '맹구', '훈이' 순으로 출력
}
반복 가능한 객체에 쓸 수 있고, 보통은 배열을 반복할 때 많이 쓴다.
const array = ['짱구', '유리', '철수', '맹구', '훈이'];
array.forEach((item)=>{
console.log(item); // '짱구', '유리', '철수', '맹구', '훈이' 순으로 출력
})
배열에서 사용할 수 있는 메서드이다.
let string = "abcde";
let array = string.split('');
console.log(array); // ['a', 'b', 'c', 'd', 'e']
let string = "abcde";
console.log(string.slice(0, 2)); // "ab"
slice(n, m)
은 n번째 인덱스에서 m-1번째 인덱스로 자른다.
let string = "abCdEfGHI";
let upper = string.toUpperCase();
console.log(upper); // "ABCDEFGHI"
let string = "abCdEfGHI";
let lower = string.toLowerCase();
console.log(lower); // "abcdefghi"
let string = "abcdeaa";
console.log(string.replace('a', '')); // 'bcdeaa'
console.log(string.replaceAll('a', '')); // 'bcde'
replace
는 'a'인 문자를 하나 찾아 ''로 변환하지만,replaceAll
은 'a'인 모든 자리를 ''로 바꾸어준다.
let string = "a14Aw%#";
console.log(string.replace(/[^a-zA-Z]/g, '')); "aAw"
replace() 함수의
첫번째 인자
의 // 안에 제거할 종류를 넣는다. 그리고 / 뒤에 g를 붙여주면 모든 문장을 검사해서 변경시켜준다. 이때 // 안에 써준 ^은 부정의 표현이다. 즉, a-z, A-Z를 제외한 문자를 ''로 변경시키게 된다.
let string = "a14Aw%#";
console.log(string.replace(/[0-9]/g, '')); // "aAw%#"
let string = "abcdefg";
console.log(str.indexOf("cde")); // 2
"cde" 문자열이 시작하는 위치를 알려준다.
let string = "abcde";
console.log(string.split("")); // ["a", "b", "c", "d", "e"]
let array = ["a", "b", "c", "d", "e"];
console.log(array.join('')); // "abcde"
join
함수는 지정된 구분자를 이용해 배열을 연결하여 새로운 문자열을 만들어준다.
let array = [1, 10, 4, -3, 2];
console.log(Math.max(...array)); // 10
console.log(Math.min(...array)); // -3
let a = -10;
console.log(Math.abs(a)); // 10
let a = 5.6;
console.log(Math.round(a)); // 6
console.log(Math.floor(a)); // 5
console.log(Math.ceil(a)); // 6
let variable = 'a';
console.log(variable.charCodeAt()); // 97
let ASCII = 97;
console.log(String.fromCharCode(ASCII)); // 'a'
키 값으로 다른 값을 사용하면 문자열로 변환
되어 저장된다.let object = new Object();
let object = {
name: '짱구',
age: 5
};
Object.keys(object); // object의 키 값을 배열로 만들어줌
Object.keys(object).length;
키 값으로 어떤 타입이나
사용 가능하다.순서를 보장
해준다. let map = new Map();
/* 객체에 값 넣기 */
map.set(1, '짱구'); // { 1: '짱구' }
map.set(2, '철수'); // { 1: '짱구', 2: '철수' }
/* 객체의 값 사용하기 */
map.get(1); // '짱구'
/* 객체 값 삭제하기 */
map.delete(2); // map = { 1: '짱구' }
/* 값이 있는지 확인 */
map.has(2); // false
map.has(1); // true
/* 객체 사이즈 확인 */
map.size; // 1
중복되는 값을 저장하는 것이 불가능
하다.값만 저장
된다.let set = new Set();
/* 객체에 값 넣기 */
set.add(1); // { 1 }
set.add(2); // { 1, 2 }
set.add(4); // { 1, 2, 4}
set.add(7); // { 1, 2, 4, 7 }
/* 객체 값 삭제하기 */
set.delete(7); // set = { 1, 2, 4 }
/* 값이 있는지 확인 */
set.has(1); // true
map.has(3); // false
/* 객체 사이즈 확인 */
set.size; // 3
/* 모든 값 제거 */
set.clear(); // set = {}
let object = { '짱구': 10, '훈이': 2, '맹구': 9};
let array = [];
for (const item in object) {
array.push([item, object[item]]);
}
/* value 기준 오름차순 정렬 */
array.sort((a, b) => a[1] - b[1]); // [['훈이', 2], ['맹구', 9], ['짱구', 10]]
/* value 기준 내림차순 정렬 */
array.sort((a, b) => b[1] - a[1]); // [['짱구', 10], ['맹구', 9], ['훈이', 2]]
/* key 기준 오름차순 정렬 */
array.sort((a, b) => a[0] > b[0] ? 1 : -1); // [['맹구', 9], ['짱구', 10], ['훈이', 2]]
/* key 기준 오름차순 정렬 */
array.sort((a, b) => a[0] > b[0] ? -1 : 1); // [['훈이', 2], ['짱구', 10], ['맹구', 9]]
class Queue {
constructor() {
this.queue = {};
this.length = (원하는 길이로 지정);
this.front = -1;
this.rear = -1;
}
size() {
return Object.keys(this.queue).length;
}
push(item) {
this.rear = (this.rear+1)%this.length;
this.queue[this.rear] = item;
}
pop() {
this.front = (this.front+1)%this.length;
let item = this.queue[this.front];
delete this.queue[this.front]
return item;
}
}
let queue = new Queue();
/* 큐에 아이템 넣기 */
queue.push(1);
queue.push(2);
/* 큐 사이즈 출력하기 */
console.log(queue.size()); // 2
/* 큐 아이템 꺼내기 */
console.log(queue.pop()); // 1
최대 힙
은 부모 노드의 값이 자식 노드의 값보다 항상 크거나 같고, 최소 힙
은 부모 노드의 값이 자식 노드의 값보다 항상 작거나 같다.class Heap {
constructor() {
this.heap = [0];
}
size() {
return this.heap.length-1;
}
push(item) {
this.heap.push(item);
let index = this.size();
while (index > 1 && this.heap[index] > this.heap[Math.floor(index/2)]) {
[this.heap[Math.floor(index/2)], this.heap[index]] = [this.heap[index], this.heap[Math.floor(index/2)]];
index = Math.floor(index/2);
}
}
pop() {
let item = this.heap[1];
this.heap[1] = this.heap.pop();
let index = 1, left = index*2, right = index*2+1;
if (this.size() === 0) { // 힙에 데이터가 없는 경우
return null;
}
if (this.size() === 1) { // 왼쪽 자식이 없는 경우
return item;
}
if (this.size() === 2) { // 오른쪽 자식이 없는 경우
if (this.heap[left] > this.heap[index]) {
[this.heap[index], this.heap[left]] = [this.heap[left], this.heap[index]];
}
return item;
}
while (this.heap[index] < this.heap[left] || this.heap[index] < this.heap[right]) {
let maxIndex = this.heap[left] > this.heap[right] ? left : right; // 왼쪽, 오른쪽 자식 중 큰 값 찾기
[this.heap[index], this.heap[maxIndex]] = [this.heap[maxIndex], this.heap[index]];
index = maxIndex;
left = index*2, right = index*2+1;
}
return item;
}
}
let heap = new Heap();
heap.push(12);
heap.push(-2);
heap.push(20);
heap.push(5);
console.log(heap.heap); // heap = [0, 20, 5, 12, -2]
console.log(heap.pop()); // 20
console.log(heap.pop()); // 12
console.log(heap.pop()); // 5
console.log(heap.heap); // heap = [0, -2]
최소 힙
은 위 코드의 조건을 바꿔 고쳐주는 방법이 있고, 위 코드를 그대로 사용한다면 push할 때 부호를 반대로 넣은 후 빼서 쓸 때 다시 부호를 반대로 붙여주면 된다.
- 예를 들어, 1, 10, -3, -2를 힙에 넣는다면 최대 힙의 경우 pop()을 하면 가장 큰 값인 10이 나온다. 즉, heap = [0, 10, 1, -3, -2]가 된다.
- 그런데 이를 최소 힙으로 바꿔 사용한다면,
1, 10, -3, -2
로 넣는게 아닌-1, -10, 3, 2
로 부호를 반대로 넣어준다. 그러면 heap = [0, 3, 2, -1, -10]이 되고, pop()을 하면 가장 큰 값으로 3이 나온다. 이를 원래대로 써주려면 다시 부호를 바꾼 -3으로 만들어준다.
let number = 12;
/* 2진수 변환 */
console.log(number.toString(2)); // '1100'
/* 8진수 변환 */
console.log(number.toString(8)); // '14'
/* 16진수 변환 */
console.log(number.toString(16)); // 'c'
let number = '1100';
console.log(parseInt(number, 2)); // 12
업데이트
💬 예정
✔️ 완료
힙 구현 (2024.06.14)객체 정렬 (2024.06.19)