728x90

✨ 배열(array)을 원하는 크기 만큼 자르고 싶을 때 사용하는 helper method(원래 값은 유지되며, copy개념이다)
(e.g., arr.slice(0,2)) 왼쪽처럼 시작(0), 끝(2) index를 지정해주면, array의 0부터 1 index까지 값을 얻어낼 수 있다.
slice( '시작', '여기 바로 앞까지' )으로 기억해주면 편하다.
Capitalize, Chunk and Merge Sort Algorithm 에서 유용하게 사용하였다.

💻Example Code

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

console.log( arr.slice(0,2) );

실행 결과(0부터 1 index까지 출력)

😋 자주 사용하지 않다가 사용하면, 어디까지 array가 잘리는지 헷갈리기 쉬운 helper method이다.

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

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

Global.parseInt()  (0) 2019.12.24
Math.sign()  (0) 2019.12.24
Math.floor()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22
Function.prototype.apply()  (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

백준 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);
728x90

백준 10818번: 최소, 최대 (https://www.acmicpc.net/problem/10818)

Final Code

😢 가장 기초적인 classic for loop을 이용해 문제를 풀었더니 시간이 조금 길어졌고, 다른 풀이도 참고해보고 싶었다.

😊 reduce helper를 이용해 조금 더 압축적인 코드를 작성할 수 있다.

reduce의 첫 번째 parameter인 acc(위에서는 minMax)에 주어진 최대(1000000)와 최소(-1000000)범위를 배열로 초기 선언 해주고, 두 번째 parameter인 value(위에서는 num)를 통해 입력 받은 숫자를 하나씩 비교하여 최종 값을 받아낼 수 있다.

즉, 입력 받은 숫자가 최대보다 작으면 minMax[0]에 저장하며 반복 비교(minMax[1]도 마찬가지)

Full Code

// 3rd Solution (reduce, minMax)

const fs = require('fs');
const input = fs
  .readFileSync('/dev/stdin')
  .toString()
  .split('\n');
const N = parseInt(input[0]);
const resultMinMax = input[1].split(' ').reduce(
  (minMax, num) => {
    const number = parseInt(num);
    minMax[0] = minMax[0] > number ? number : minMax[0];
    minMax[1] = minMax[1] < number ? number : minMax[1];
    return minMax;
  },
  [1000000, -1000000]
);

console.log(resultMinMax.join(' '));

// 2nd Solution (classic for loop)

// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().split('\n');
// const N = parseInt(input[0]);
// const numArr = input[1].split(' ').map(num => {
//     num = parseInt(num);
//     return num;
// });

// let max = numArr[0];
// let min = numArr[0];

// for (let i = 0; i < numArr.length; i++) {
//   if (numArr[i] > max) {
//     max = numArr[i];
//   }

//   if (numArr[i] < min) {
//     min = numArr[i];
//   }
// }

// console.log(min + ' ' + max);

// 1st Solution(Spread in VSC)

// const input = ['5', '20 10 35 30 7'];
// const N = parseInt(input[0]);
// const numArr = input[1].split(' ').map(num => {
//   num = parseInt(num);
//   return num;
// });

// const max = Math.max(...numArr);
// const min = Math.min(...numArr);

// console.log(numArr);
// console.log(min + ' ' + max);
728x90

백준 1110번: 더하기 사이클 (https://www.acmicpc.net/problem/1110)

 

Code

const fs = require('fs');
let newNum = fs.readFileSync('/dev/stdin').toString();
const ORIGIN = parseInt(newNum);
let counter = 0;
 
while (newNum !== ORIGIN || counter === 0) {
newNum = (newNum % 10) * 10 + ((parseInt(newNum / 10) + (newNum % 10)) % 10);
counter++;
}
 
console.log(counter);
 
// Timeout code (시간 초과 코드)
 
// const fs = require('fs');
// let input = fs.readFileSync('/dev/stdin').toString();
 
// if (parseInt(input) < 10) {
// input = '0' + input;
// }
 
// let newNum = input;
// let counter = 0;
// let sum = 0;
 
// while (newNum !== input || counter === 0) {
// sum = parseInt(newNum[0]) + parseInt(newNum[1]);
 
// if (sum < 10) {
// sum = '0' + sum.toString();
// } else {
// sum = sum.toString();
// }
 
// newNum = newNum[1] + sum[1];
// counter++;
// }
 
// console.log(counter);

😢 너무 순진하게 문제 그대로를 코드로 작성하려 하다보니, 코드가 길어져 시간 초과가 발생하였다.

😊'10의 자릿수'와 '1의 자릿수'를 구하는 방법만 알면 쉽게 해결할 수 있다.

10의 자릿수 : (newNum%10)*10

✔ 1의 자릿수 : ( parseInt( newNum/10 ) + ( newNum%10 ) ) % 10

1️⃣초기값(===새로운 수)2️⃣ 각 자릿수 더하기 3️⃣ 새로운 수
26 👉 2+6=08 👉 68
68 👉 6+8=14 👉 84
84 👉 8+4=12 👉42
42 👉 4+2=06 👉26
2️⃣식에서 각 자릿수를 더할 때 '1의 자릿수'를 '10의 자릿수'로 만들어 주기 위해 ' 10의 자릿수'식 사용
2️⃣식에서 각 자릿수를 더한 결과값의 '1의 자릿수'를 구하기 위해 ' 1의 자릿수'식 사용
위의 두 값을 합하면 '새로운 수'를 구할 수 있다. (반복)

+ Recent posts