728x90

Q. 주어진 string을 정반대로 뒤바꾸고 return하라.

--- Examples
reverse('apple') === 'leppa'
reverse('hello') === 'olleh'
reverse('Greetings!') === '!sgniteerG'

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/9cc55eac880eb89db3649ea8e440a311caa4ef48
https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/3437f358a612996ee0baa02a8ff2e1f5a414ef3c
https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/198f985e17d687765d99ee0bc31f739c587b4a50

😢 reverse() helper를 이용하여 쉽게 해결할 수 있지만, 다른 방법으로도 풀 수 있는 것이 중요하다.

😊 평소 자주 사용하지 않았던, for of loop와 reduce를 이용하여 쉽게 해결할 수 있었다.

 String.prototype.split()

split() 의 괄호 안에 separator를 지정하여 string을 array로 변환할 수 있다.

✔ Array.prototype.reverse()

method명 그대로 array의 순서를 정반대로 뒤바꿀 수 있다.
따라서 해당 값이 array가 아니라면, split('')을 이용해 array로 변경해주는 것이 중요하다.

Array.prototype.join()

join() 의 괄호 안에 separator를 지정하여 array를 string으로 변환할 수 있다.

Array.prototype.reduce()

reduce() 의 괄호 안에 reducer function을 작성하여 array 값을 다룰 수 있다. 
간단히 설명하자면, 첫 번째 arguments는 accumulator, 두 번째 arguments는 currentValue이며,
위의 3번째 소스코드처럼 rev에 char를 하나씩 계속 더하는 방식으로 결과를 도출해냈다.
자세한 내용은 helper methods category에서 다루도록 하겠다.

✔ for ... of

classic for loop 보다 fancy한 for loop이다.
for(let value of array){} 형식으로 사용하며, array의 첫 번째 값부터 마지막 값까지 순서대로 value에 전달한다.
평소 classic for loop을 이용하면 index 선언 순서가 헷갈리거나 오타가 발생할 수 있는데, 그것을 방지하는 것에 좋다.
다른 category에서 더 자세히 다루어 보겠다.

Full Code

function reverse(str) {
return str.split('').reduce((rev, char) => char + rev, '');
}
 
// function reverse(str) {
// return str
// .split('')
// .reverse()
// .join('');
// }
 
// function reverse(str) {
// let reversed = '';
 
// for (let character of str) {
// reversed = character + reversed;
// }
 
// return reversed;
// }
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

✨ 소수점 이하를 버리기 위한 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);
}
}

+ Recent posts