728x90

오류 메세지
npm install
.babelrc에 plugin 추가

.babelrc 파일에 ["@babel/transform-runtime"] 추가해야 한다.

동기 비동기 작업을 수행할때 Babel 사용시 위의 두가지 종속성을 설치하고 .babelrc 파일을 수정해야 한다.

728x90

https://www.acmicpc.net/problem/2231

Code

최종 제출 코드

😢 '백준 4673번: 셀프넘버'를 풀었다면 쉽게 풀 수 있는 문제

😊 브루트 포스로 1부터 생성자가 있는 숫자들을 구해주고( d(n) ), N의 생성자가 여러 개라면 배열에 넣어준다.
최종적으로 생성자가 있다면 Math.min을 이용해 최솟값을 출력해주고, 없다면 0을 출력해주면 된다.
각 자릿수를 합하는 것은 위의 셀프넘버를 참고하면 된다.

참고로, 속도는 while로 자릿수를 나누는 게 더 빠르다(Full Code의 2nd Solution code 참고)

Full Code (https://github.com/DasolPark/Dasol_JS_Algorithm/tree/master/Baekjoon)

// Sum of break up(분해합)
 
// 1st Solution
 
// For submit
 
// const fs = require('fs');
// const input = parseInt(fs.readFileSync('/dev/stdin').toString().trim());
 
// For local test
const input = 216;
const constructorArr = [];
 
function d(n) {
const N = n.toString().split('');
 
return n + N.reduce((acc, num) => (acc += parseInt(num)), 0);
}
 
for (let i = 1; i <= input; i++) {
if (d(i) === input) {
constructorArr.push(i);
}
}
 
if (constructorArr.length) {
console.log(Math.min.apply(null, constructorArr));
} else {
console.log(0);
}
 
// 2nd Solution
 
// For submit
 
// const fs = require('fs');
// const input = parseInt(fs.readFileSync('/dev/stdin').toString().trim());
 
// For local test
// const input = 216;
// const constructorArr = [];
 
// function d(n) {
// let temp = n;
// let sum = n;
 
// while (temp) {
// sum += temp % 10;
// temp = parseInt(temp / 10);
// }
 
// return sum;
// }
 
// for (let i = 1; i <= input; i++) {
// if (d(i) === input) {
// constructorArr.push(i);
// }
// }
 
// if (constructorArr.length) {
// console.log(Math.min.apply(null, constructorArr));
// } else {
// console.log(0);
// }
728x90

https://www.acmicpc.net/problem/2798

Code

최종 제출 코드

😢 말 그대로 브루트 포스

😊 어떠한 요행을 바라기보다는 그냥 브루프 포스다.
반복문 돌려서 모든 경우의 수를 다 계산한다.

카드 3개의 조합의 합을 구해야 하므로 3개의 중첩 for loop을 이용해 해결 가능하다.

5 6 7 8 9 카드들을 위의 중첩문으로 실행하면 다음과 같은 순서로 진행된다.

[0][1][2] 5 6 7 = 18
[0][1][3] 5 6 8 = 19
[0][1][4] 5 6 9 = 20
[0][2][3] 5 7 8 = 20
[0][2][4] 5 7 9 = 21
[0][3][4] 5 8 9 = 22
[1][2][3] 6 7 8 = 21
[1][2][4] 6 7 9 = 22
[1][3][4] 6 8 9 = 23
[2][3][4] 7 8 9 = 24

위의 합 중에 M보다 작거나 같은 것은 21

Full Code (https://github.com/DasolPark/Dasol_JS_Algorithm/tree/master/Baekjoon)

// Blackjack
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
const input = ['5 21', '5 6 7 8 9'];
const NM = input
.shift()
.split(' ')
.map(num => parseInt(num));
const N = NM.shift();
const M = NM.shift();
const cardArr = input
.shift()
.split(' ')
.map(num => parseInt(num));
let max = 0;
 
for (let i = 0; i < N - 2; i++) {
for (let j = i + 1; j < N - 1; j++) {
for (let k = j + 1; k < N; k++) {
let sum = cardArr[i] + cardArr[j] + cardArr[k];
if (sum > max && sum <= M) {
max = sum;
}
}
}
}
 
console.log(max);
728x90

https://www.acmicpc.net/problem/2750

Code

최종 제출 코드

😢 기본 문제

😊 JavaScript built-in method인 sort()를 사용해주면 된다.
문자를 정렬할 때는 sort()를 그냥 써줘도 되지만, 숫자를 정렬할 때는 sort((a, b) => a-b); 로 써줘야 한다.
난 for ... of를 사용하고 좋아하지만, 속도(?)와 참고하는 사람들 때문에 정석 버전으로 캡쳐했다.

Full Code (https://github.com/DasolPark/Dasol_JS_Algorithm/tree/master/Baekjoon)

// Sort numbers(Ascending order)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n').map(num => parseInt(num));
 
// For local test
const input = [5, 5, 2, 3, 4, 1];
const N = input.shift();
const sorted = input.sort((a, b) => a - b);
 
for (let i = 0; i < N; i++) {
console.log(sorted[i]);
}
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n').map(num => parseInt(num));
 
// For local test
// const input = [5, 5, 2, 3, 4, 1];
// input.shift();
// const sorted = input.sort((a, b) => a - b);
 
// for (let num of sorted) {
// console.log(num);
// }
728x90

https://www.acmicpc.net/problem/7568

Code

최종 제출 코드

😢 브루트 포스 감을 익힌 문제. 간단하다.

😊 2차원 배열로 키와 몸무게를 정렬해주고 중첩 for loop을 이용하면 된다.
첫 번째 사람부터 마지막 사람까지 본인보다 큰 몸무게&&키가 있다면 counter++; 해주고,
마지막 rank 배열에 저장할 때 +1을 한 번 더 해주면 그게 본인 순위가 된다.

모든 경우의 수를 비교하는 '브루트 포스(Brute-force)'

Full Code (https://github.com/DasolPark/Dasol_JS_Algorithm/tree/master/Baekjoon)

// A big person
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
const input = ['5', '55 185', '58 183', '88 186', '60 175', '46 155'];
const T = input.shift();
const kgCmTable = input.map(kgCm => kgCm.split(' ').map(num => parseInt(num)));
const rank = [];
 
for (let i = 0; i < T; i++) {
let counter = 0;
for (let j = 0; j < T; j++) {
if (i !== j) {
if (
kgCmTable[i][0] < kgCmTable[j][0] &&
kgCmTable[i][1] < kgCmTable[j][1]
) {
counter++;
}
}
}
rank.push(counter + 1);
}
 
console.log(rank.join(' '));
728x90

✨ 절대값을 이용한 계산이 필요할 때 사용할 수 있는 helper method

💻Example Code

const x1 = 5;
const x2 = 3;

console.log(x2-x1);
console.log(x1-x2);
console.log(Math.abs(x2-x1));
console.log(Math.abs(x1-x2));

🧨 두 점 사이의 거리 등 다양한 계산에서 활용할 수 있다.

👉 자세한 내용은 https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/abs

 

Math.abs()

Math.abs() 함수는 주어진 숫자의 절대값을 반환합니다.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.prototype.localeCompare()  (0) 2020.02.20
Math.round()  (0) 2020.02.16
Math.PI  (0) 2020.01.28
Array.prototype.forEach()  (0) 2020.01.23
Math.pow()  (0) 2020.01.22
728x90

https://www.acmicpc.net/problem/1002

Code

최종 제출 코드

😢 여러가지 고려해야할 경우를 찾아내는 것이 힘들었다.

😊
1. 원이 두 점에서 만나는 경우 (2)( r2 - r1 < d < r1 + r2)
2. 두 원이 외접하는 경우 (1)( d === r1 + r2 )
3. 두 원이 내접하는 경우 (1)( d === r2 - r1 && d !== 0 )
4. 한 원이 다른 원을 포함하는 경우 (0)( d < r2 - r1 )
5. 두 원이 떨어져 만나지 않는 경우 (0)( d > r1 + r2 )
6. 두 원이 일치하는 경우 (-1)( d === 0, r1 === r2 )

중점 사이의 거리를 구하고, 위 6가지 경우만 조건문으로 분류해주면 된다.

참고 자료 https://mathbang.net/101

 

두 원의 위치관계, 내접, 외접

위치관계 또 나오네요. 이번에는 두 원의 위치관계에요. 위치관계 마지막이니까 정신 바짝 차리고 따라오세요. 원과 직선의 위치관계, 원의 할선과 접선, 접점에서 했던 것처럼 두 원이 어떤 관계가 있는지 그때..

mathbang.net

Full Code (https://github.com/DasolPark/Dasol_JS_Algorithm/tree/master/Baekjoon)

// Turret
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
const input = ['3', '0 0 13 40 0 37', '0 0 3 0 7 4', '1 1 1 1 1 5'];
const T = parseInt(input.shift());
 
for (let i = 0; i < T; i++) {
const xyrxyr = input[i].split(' ').map(num => parseInt(num));
const x1 = xyrxyr.shift();
const y1 = xyrxyr.shift();
let r1 = xyrxyr.shift();
const x2 = xyrxyr.shift();
const y2 = xyrxyr.shift();
let r2 = xyrxyr.shift();
 
const dx = x1 - x2;
const dy = y1 - y2;
if (r1 > r2) {
// r1 <= r2로 정의
const temp = r1;
r1 = r2;
r2 = temp;
}
const rSum = (r1 + r2) * (r1 + r2);
const rSub = (r2 - r1) * (r2 - r1);
const d = dx * dx + dy * dy; // 중점 사이의 거리
 
// 1. 원이 두 점에서 만나는 경우 (두 점)(r2 - r1 < d < r1 + r2)
if (d < rSum && d > rSub) {
console.log(2);
// 2. 두 원이 외접하는 경우 (한 점)( d = r1 + r2)
// 3. 두 원이 내접하는 경우 (한 점)( d = r2 - r1 && d != 0)
} else if (d === rSum || (d === rSub && d !== 0)) {
console.log(1);
// 4. 하나의 원이 다른 원을 포함하는 경우 (못 만남)( d < r2 - r1 )
// 5. 두 원이 멀리 떨어져 만나지 않는 경우 (못 만남)( d > r1 + r2 )
} else if (d < rSub || d > rSum) {
console.log(0);
// 6. 두 원이 일치하는 경우 (무수히)( d = 0, r1 = r2 )
} else if (d === 0) {
if (r1 === r2) {
console.log(-1);
} else {
console.log(0);
}
}
}
728x90

✨ PI(파이)를 이용한 계산이 필요할 때 사용할 수 있는 helper method

💻Example Code

const radius = 2
const areaOfCircle = radius * radius * Math.PI;

console.log( areaOfCircle );
console.log( Math.PI );

실행 결과

🧨 원의 넓이를 구하는 공식: 반지름*반지름*PI(파이)

😋 소수점 아래를 조정하고 싶다면 toFixed()를 사용해주면 된다. 링크 참고(https://dpsc615.tistory.com/14)

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI

 

Math.PI

The Math.PI property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159:

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Math.round()  (0) 2020.02.16
Math.abs()  (0) 2020.01.28
Array.prototype.forEach()  (0) 2020.01.23
Math.pow()  (0) 2020.01.22
Math.random()  (0) 2020.01.18
728x90

https://www.acmicpc.net/problem/3053

Code

최종 제출 코드

😢 택시 기하학과 유클리드 기하학을 검색한 후, 이해하고 풀면 되는 문제

😊 유클리드 기하학에서 반지름이 R인 원이 넓이'반지름*반지름*PI'이므로 Math.powMath.PI를 이용하여 풀었고,
택시 기하학에서 반지름이 R인 원의 넓이마름모와 같으므로, '밑변*높이*2'(직사각형 넓이*2라고 생각)로 풀어주면 된다.

Full Code (https://github.com/DasolPark/Dasol_JS_Algorithm/tree/master/Baekjoon)

// Taxi geometry(Euclid geometry)
 
// For submit
 
// const fs = require('fs');
// const input = parseInt(fs.readFileSync('/dev/stdin').toString().trim());
 
// For local test
const input = 1;
 
function Euclid(radius) {
return Math.pow(radius, 2) * Math.PI;
}
 
function taxi(radius) {
return Math.pow(radius, 2) * 2;
}
 
console.log(Euclid(input).toFixed(6));
console.log(taxi(input).toFixed(6));
728x90

Object를 생성할 때마다, 뭔지 모르게 항상 붙는 __proto__가 있다.
또한 출처를 알 수 없는 .length, split(), toString()를 우리는 항상 사용해 왔다.
이것들은 뭘까? 어디서 왔고? 어디서 생겼을까? 라는 생각으로 시작하면 될 것 같다.

먼저, JavaScript는 객체지향 언어다.
하지만, Java, Python과 다르게 class기반의 객체지향 언어가 아니고, prototype 기반의 객제지향 언어다.
(ES5 이후 class를 지원하지만, class를 객체지향의 기반으로 사용하고 있지 않다)

생성자로 사용하기 위한 fuction을 작성해보자.

Bird constructor, Bird prototype

위 결과를 보면 함수를 생성했는데, constructor__proto__가 함께 생성된 것을 볼 수 있다.

간단히 말하자면, constructor해당 Object의 원본(Bird 자신)을 가리키며, __proto__ Object prototype을 가리킨다.
Object prototype은 JavaScript에서 생성되는 모든 것들의 조상이라고 생각하면 된다
(앞서 말한 toString(), split() 등 모든 built-in method를 가지고 있다)

위 생성자를 이용해 bird1과 bird2를 instance로 찍어보자.

bird1, bird2 Instance

bird1를 출력해보면 자신만의 name, color와 생성자가 가지고 있던 sing function 그리고 __proto__가 생성된 것을 볼 수 있다.
그리고 __proto__를 누르면 function 생성자를 선언할 때 볼 수 있던 constructor__proto__다시 볼 수 있다.

이런식으로, prototype chain을 통해 연속적으로 자신의 조상 prototype을 참조한다.

즉, 우리가 JavaScript안에서 생성하는 Array, String, Object, function 등 모두 함수를 통해 생성되며,
단순히 하나의 Object만 생성되는 것이 아니라, constructor와 Object prototype을 참조하며 생성된다.
또한, 각 instance마다 property를 추가할 필요 없이 prototype을 이용해 memory를 공유할 수 있다.

참고 자료 https://dev.to/lydiahallie/javascript-visualized-prototypal-inheritance-47co

 

🎉👨‍👩‍👧‍👧 JavaScript Visualized: Prototypal Inheritance

 

dev.to

 

'JavaScript > JavaScript' 카테고리의 다른 글

Hoisting(호이스팅)  (0) 2020.01.24
Event Library(이벤트 관리 라이브러리를 만들어보자)  (0) 2020.01.15

+ Recent posts