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

백준 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