728x90

✨ 소수점 이하를 버리기 위한 Math의 helper method

(e.g., Math.floor(arr.length/2)) arr.length === 5 라고 가정할 때, 2라는 값을 도출할 수 있다.
Pyramid and Merge Sort Algorithm 등 여러곳에서 유용하게 사용했다.
(주로 array의 중간(midpoint or center)지점을 찾을 때 사용해왔으며, 그 외에도 다양한 곳에서 자주 사용된다)

💻Example Code

const arr = [1, 2, 3, 4, 5];

console.log( Math.floor(arr/2) );

실행 결과(2.5에서 소수점 이하를 버리고 2 출력)

😋 array의 index는 기본적으로 0부터 시작하기 때문에 홀수 개수의 array가 있을 때 center를 찾기에 유용하다.
특히, Array.prototype.slice() 와 연계하여 사용할 때 편하다. slice(begin index, End index) 형식으로 array(0,2)처럼 array를 자른다면, 0부터 1까지 index의 값만 slice 되기 때문이다.

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

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

Math.sign()  (0) 2019.12.24
Array.prototype.slice()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22
Function.prototype.apply()  (0) 2019.12.22
String.prototype.split()  (0) 2019.12.22
728x90

✨ 소수점을 표시하기 위한 helper method

(e.g., 숫자변수.toFixed(2)) 왼쪽처럼 숫자값이 들어있는 변수에 toFixed(2)를 이용해주면 소수점 아래 2번째 값까지 표시가 가능하다.
기본적으로 JavaScript의 숫자는 Number로 통합되어 관리되고 표시되지만, int가 아니며 floating  point 속성을 가지고 있다.
(값의 통일성을 위해 의도적으로 소수점을 맞추고 싶을 때 유용할 것 같다. default는 반올림(round)이다)

 

💻Example Code

const num = 10.567

console.log(num.toFixed(2));

실행 결과 (10.567의 소수점 아래 2번째에서 반올림되어 1.57 출력)

😋 아직 어딘가에서 사용해보지는 않았지만, 백준 Algorithm을 풀면서 출력 형식을 똑같이 맞춰줘야하나?
생각하며 검색하다가 찾은 helper method이다. 언젠가는 분명 사용할 일이 있을 것 같다.

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

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

Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
Function.prototype.apply()  (0) 2019.12.22
String.prototype.split()  (0) 2019.12.22
String.prototype.trim()  (0) 2019.12.22
728x90

✨기존 function에 this(or null)와 arguments(array or an array-like object)를 넣어 함께 불러낼 수 있는 helper method

(e.g., Math.max.apply(null, array)) 왼쪽처럼 Math.max에 apply(null, array)를 적용해주면 array안에 있는 수 중에
가장 큰 수를 손쉽게 구할 수 있다.
재귀(Recursive)함수에서 Dynamic Programming(Memoize)을 사용할 때도 적용할 수 있다.

 

💻Example Code

const arr = [1, 2, 3, 4, 5, 6, 7];
const max = Math.max.apply(null, arr);

console.log(max);

실행 결과(1~7 중에 가장 큰 수는 7)

😋 평소에 자주 쓸 일은 없었지만, Algorithm을 공부하면서 종종 사용하게 되었다.
max를 구하기 위한 classic 방식은 모두 이해하고 알고 있으니, 앞으로 간략한 Math.max.apply()를 주로 이용해보자.
단, 첫 번째 this(or null)의 사용법은 조금 더 익힐 필요가 있겠다.

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

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

Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22
String.prototype.split()  (0) 2019.12.22
String.prototype.trim()  (0) 2019.12.22
728x90

백준 1546번: 평균(New average)(https://www.acmicpc.net/problem/1546)

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/1b5c7ef837e647f988486adb3b3656a9cd9df9eb

😢 역시 쉬운 문제라 내 방식대로 금방 풀었지만, 백준 형식에 맞지 않는 것인지 계속 '틀렸습니다'가 출력되었다.
이렇게 저렇게 한 10번은 바꿔보았지만, 틀린 이유를 찾지 못했다. 생각날 때마다 시도해봐야겠다. (위의 코드는 정답 코드)

😊 이번 문제에서 Function.prototype.apply()와 Number.prototype.toFixed()를 학습할 수 있었다.

Function.prototype.apply() 관련
최대값을 구하기 위해서 주로 3가지 방법을 사용했었다.
1. 적은 수의 값들에서 Max를 구할 때는 'Math.max(values...)
2. classic for loop을 이용하여 하나씩 비교하여 최종 Max값을 구하는 방법
3. 백준에서는 적용되지 않지만, Math.max(...values)처럼 ES2015 'Spread'사용하여 구하는 방법

하지만, 위의 13번째 code인 Math.max.apply(null, grades) 를 이용하면 보다 쉽게 max를 구할 수 있다.
간단히 설명하자면, 두 번째 arguments에 array(or an array-like object)를 넣어주면 된다.

Number.prototype.toFixed()
위의 helper method를 이용해 소수점 아래의 수를 표시할 수 있다. (e.g., toFixed(2)는 소수점 아래 2번째까지 출력)

Full Code

// 3rd Solution (submitted)
 
// For Submit
// const input = require('fs')
// .readFileSync('/dev/stdin')
// .toString()
// .split('\n');
 
// For local Test
const input = ['3', '10 20 30'];
const N = parseInt(input[0]);
const grades = input[1].split(' ');
const max = Math.max.apply(null, grades);
let sumNewGrades = 0;
 
for (var i = 0; i < grades.length; i++) {
sumNewGrades += (grades[i] / max) * 100;
}
 
console.log(sumNewGrades / N);
 
// 2nd Solution (Wrong only in baekjoon)
 
// For local test
 
// const input = ['3', '10 20 30'];
// const N = parseInt(input[0]);
// const grades = input[1].split(' ').map(num => {
// return (num = parseInt(num));
// });
// const newGrades = [];
// let max = 0;
// let sumNewGrades = 0;
// let result = 0;
 
// for (let i = 1; i < N; i++) {
// if (grades[i] > max) {
// max = grades[i];
// }
// }
 
// for (let grade of grades) {
// newGrades.push((grade / max) * 100);
// }
 
// for (let grade of newGrades) {
// sumNewGrades += grade;
// }
 
// result = sumNewGrades / newGrades.length;
 
// console.log(result.toFixed(2));
 
// 1st Solution (Spread - ES2015) (Wrong only in baekjoon)
 
// For local test
 
// const input = ['3', '40 80 60'];
// const N = parseInt(input[0]);
// const grades = input[1].split(' ').map(num => (num = parseInt(num)));
// const max = Math.max(...grades);
// const newGrades = [];
// let result = 0;
 
// for (let grade of grades) {
// newGrades.push((grade / max) * 100);
// }
 
// for (let grade of newGrades) {
// result += grade;
// }
 
// console.log(result / grades.length);
728x90

✨ '단순 문자열'을 '배열 문자열'로 변환하기 위해 꼭 필요한 helper method이다.

(e.g., 'Hello World') 왼쪽의 string이 있을 때, split(' ')을 사용해주면 ' '(space)기준으로 문자열을 나누어 새로운 배열이 생성된다. (기본적으로 split('separator') 형식으로 사용하며, ' '(space), '\n'(Line Feed) 등 여러가지 separator를 넣어 사용한다)

 

💻Example Code

const str = 'Hello World';

console.log(str);
console.log(str.split(' '));

실행 결과(위 str, 아래 str.split(' '))

위 'Hello World'는 단순 str의 출력이며, 아래 배열(array)은 str.split(' ')의 출력 결과다.

😋 split() helper method은 정말 많은 곳에서 쓰인다.
최근 백준 algorithm을 풀 때, 입력값의 마지막에 \n가 붙어있었다.
split('\n')을 통해 배열로 전환되면서 마지막 index에 '' 공백 배열 문자열이 하나 더 추가되었고, 이것이 답을 도출하는데 오류를 발생시켰다. 
만약 \n(Line Feed)을 이용해 문자열을 분리해야 할 때가 온다면, trim()을 이용하여 마지막 \n 제거를 한 후 split('\n')할 것을 추천한다.

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

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

Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22
Function.prototype.apply()  (0) 2019.12.22
String.prototype.trim()  (0) 2019.12.22
728x90

✨white space를 제거하여, 정확한 string값을 제어하기 위해 꼭 필요한 helper method이다.

(e.g., '   Hello World   ') 왼쪽의 string이 있을 때, trim을 사용해주면 문자열 기준 '앞', '뒤'의 white space를 없애준다.
(white space는 characters(space, tab, no-break space, etc.) 와 terminator characters (LF, CR, etc.)이 해당된다)

 

💻Example Code

let str = '   Hello World   ';

console.log(str.trim()); // 'Hello World';

실행 결과(위와 아래의 공백이 다른 것을 볼 수 있다)

위는 console.log(str.trim()); 의 실행결과이며, 아래는 console.log(str);의 실행결과이다.

😋 trim() helper function은 백준에서 algorithm을 풀 때, 받아오는 입력값을 정리할 때 유용하게 사용하고 있다.

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

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

Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22
Function.prototype.apply()  (0) 2019.12.22
String.prototype.split()  (0) 2019.12.22
728x90

백준 3052번: 나머지(https://www.acmicpc.net/problem/3052)

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/293abe528c7ebc870d22b8acbab901c873dffbf4

😢 쉬운 문제였기 때문에 금방 풀었으나, 문제는 뜻밖의 부분에 있었다.
값을 읽어올 때, trim()을 적용시켜주지 않아서, 마지막 공백 ''이 들어왔기 때문이다.
그래서 ''%42=0이 되어버렸고, theRestMap Object key값 0의 값이 1만큼 올라갔다.
따라서, 결과값이 항상 1만큼 더 높게 나와 '틀렸습니다' 결과를 받았다.

😊 Object를 하나 선언해주고, for of loop을 이용해 해당 나머지값(key)이 중복될 때마다 값(value)를 1씩 증가해준다.
그런 후 마지막에 Object.keys(theRestMap).length 를 출력하여 key의 개수(길이)만큼 출력하면 그것이 나머지의 개수다.

Full Code

// 2nd Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs
// .readFileSync('/dev/stdin')
// .toString()
// .trim()
// .split('\n');
 
// For local test
 
const input = ['39', '40', '41', '42', '43', '44', '82', '83', '84', '85'];
const Rest = [];
let counter = 0;
 
for (let i = 0; i < input.length; i++) {
const RestNum = parseInt(input[i]) % 42;
if (!Rest[RestNum]) {
Rest[RestNum] = 1;
counter++;
}
}
 
console.log(counter);
 
// 1st Solution ( Wrong but this is correct in local)
// 아마 Object.keys가 적용되지 않는 듯? 인줄 알았으나 값을 가져오는 과정에 trim()을 추가하니 해결 되었다.
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().split('\n');
 
// For local test
 
// const input = ['39', '40', '41', '42', '43', '44', '82', '83', '84', '85'];
// const theRestMap = {};
 
// for (let num of input) {
// const theRest = num % 42;
// theRestMap[theRest] = theRestMap[theRest] ? theRestMap[theRest] + 1 : 1;
// }
 
// console.log(Object.keys(theRestMap).length);
728x90

백준 2577번: 숫자의 개수(https://www.acmicpc.net/problem/2577)

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/0a43c98b28beb602c12e983748c933e2b689708d

😊 charMap Object를 만들고, for of loop을 이용해 출현한 숫자는 key로 중복되는 값은 value로 늘려 저장한다.
그런 후 classic for loop을 이용해 해당 숫자가 있다면 해당 숫자의 출현 개수를, 없다면 0을 출력하여 해결한다.

Full Code

// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().split('\n');
 
// For Local Test
const input = ['150', '266', '427'];
const result = input[0] * input[1] * input[2];
const charMap = {};
 
for (let num of result.toString()) {
charMap[num] = charMap[num] ? charMap[num] + 1 : 1;
}
 
for (let i = 0; i < 10; i++) {
if (charMap[i]) {
console.log(charMap[i]);
} else {
console.log(0);
}
}
728x90

백준 2920번: 음계(https://www.acmicpc.net/problem/2920)

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/9935e611cba4242d667fa34aea394310a6a7f8fa

😢 처음에는 단순하게 '12345678'같은 string을 이용해 비교하여 풀었으나,
One-demensional Array라는 것에 의미를 두고 Array의 Index를 이용하여 다시 풀었다.

😊 i는 0부터 arr.length까지 증가한다는 전제 조건을 두고,
arr[i] - arr[i+1] = -1이 연속하여 7번 나온다면 1부터 8까지 오름차순인 ascending scale, 
arr[i] - arr[i+1] = 1이 연속하여 7번 나온다면 8부터 1까지 내림차순인 descending scale,
앞의 2가지 경우에 해당하지 않는다면, mixed scale 를 출력한다.

Full Code

// 2nd Solution(current - after)
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().split(' ');
 
// For Local Test
const input = ['1', '2', '3', '4', '5', '6', '7', '8'];
// const input = ['8', '7', '6', '5', '4', '3', '2', '1'];
// const input = ['8', '1', '7', '2', '6', '3', '5', '4'];
let ascending = 0;
let descending = 0;
 
for (let i = 0; i < input.length - 1; i++) {
if (input[i] - input[i + 1] === -1) {
ascending++;
} else if (input[i] - input[i + 1] === 1) {
descending++;
}
}
 
if (ascending === 7) {
console.log('ascending');
} else if (descending === 7) {
console.log('descending');
} else {
console.log('mixed');
}
 
// 1st Solution(string)
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().split(' ');
 
// For Local Test
// const input = ['1', '2', '3', '4', '5', '6', '7', '8'];
// const input = ['8', '7', '6', '5', '4', '3', '2', '1'];
// const input = ['8', '1', '7', '2', '6', '3', '5', '4'];
// const scale = parseInt(input.join(''));
// const ascending = 12345678;
// const descending = 87654321;
 
// if (scale === ascending) {
// console.log('ascending');
// } else if (scale === descending) {
// console.log('descending');
// } else {
// console.log('mixed');
// }
728x90

백준 2562번 최댓값(https://www.acmicpc.net/problem/2562)

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/0992b220965434c4c6fb8793841b355e7cdeeaed

 

😢 Sort를 이용해서 최댓값을 구한 후 Index를 구하려 했으나, 돌아가는 길 같아서 바로 접었다.

😊 classic for loop을 이용해 모든 값과 비교 후 max를 구하고,
해당 값이 max라면 그 값의 index+1를 저장하여 몇 번째 값인지 구하였다.

Full Code

// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().split('\n');
const input = ['3', '29', '38', '12', '57', '74', '40', '85', '61'];
const inputToInt = input.map(num => (num = parseInt(num)));
let max = 0;
let idx = 0;
 
for (let i = 0; i < inputToInt.length; i++) {
if (inputToInt[i] > max) {
max = inputToInt[i];
idx = i + 1;
}
}
 
console.log(max);
console.log(idx);

+ Recent posts