728x90

Q. 주어진 string에서 가장 많이 쓰인 char를 찾아서 출력하라.

--- Examples
maxChar("abcccccccd") === "c"
maxChar("apple 1231111") === "1"

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/8db5e8446c13282c8bc305ef53d0ccbedf9bd607

😢 Object를 만드는 방법에 익숙하지 않았는데, 이번 기회를 통해 익숙해질 수 있었다.
마찬가지로, for ... of와 for ... in을 사용하는 것도 익숙해질 수 있었다.

😊 Map(Object)을 만들어서 각 문자(key)의 빈도수(value)를 저장하고, 최대값(max)을 구하여, 가장 많이 쓰인 문자(maxChar)를 출력하는 방식으로 해결하면 된다.

✔ object map

object는 key와 value를 가지고 있다. arr[1] = 'a'; 처럼 배열에 저장하듯 객체를 저장하면 된다.
charMap[char] = charMap[char] ? charMap[char] + 1 : 1;
charMap object에 해당 char가 있으면 +1, 없으면 1로 key와 value를 선언해준다.

✔ for ... of

for( let char of str ) {} 처럼 입력값으로 받은 str의 character를 순서대로 하나씩 가져와 loop을 실행하는 for loop이다.
classic for loop처럼 index를 하나하나 지정해줘야하는 번거로움을 없앨 수 있다.(오타 발생 사전 제거에 유용함)

✔ for ... in

for( let char in charMap ) {} 처럼 charMap object의 key를 순서대로 하나씩 가져와 loop을 실행하는 for loop이다.
객체(object)를 loop하고 싶을 때 사용할 수 있다.

 

Full Code

 

function maxChar(str) {
const charMap = {};
let max = 0;
let maxChar = '';
 
for (let char of str) {
if (charMap[char]) {
charMap[char]++;
} else {
charMap[char] = 1;
}
}
 
for (let char in charMap) {
if (charMap[char] > max) {
max = charMap[char];
maxChar = char;
}
}
 
return maxChar;
}
728x90

Q. 주어진 string의 회문 구조를 파악하고, 맞으면 true 틀리면 false를 return하라.

--- Examples
palindrome("abba") === true
palindrome("abcdefg") === false

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/efd69d6b976fab583958556518cf5b3162275d67
https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/efd69d6b976fab583958556518cf5b3162275d67

😢 reverse int and string에서 배웠던 Skill로도 충분했지만, 다른 방법을 적용해보고 싶었다.

😊 every()를 이용하여 주어진 string argument를 검사하는 방식을 배울 수 있었다.

✔ Array.prototype.every()

every() 괄호 안에 test function을 작성하여, 해당 array값을 이용해 test할 수 있다.
위의 소스코드에서는 char === str[str.length - i - 1]을 이용하여 맨 앞과 맨 뒤의 값을 하나씩 이동하며 비교하였다.
자세한 every() 사용법은 helper methods category에서 다루도록 하겠다.

Full Code

function palindrome(str) {
return str.split('').every((char, i) => {
return char === str[str.length - i - 1];
});
}
 
// function palindrome(str) {
// let reversed = str
// .split('')
// .reverse()
// .join();
// return str === reversed;
// }
728x90

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

--- Examples
reverseInt(15) === 51
reverseInt(981) === 189
reverseInt(500) === 5
reverseInt(-15) === -51
reverseInt(-90) === -9

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/ccd99f2e87c5836d5e0b22793caf882e652d9529
https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/ccd99f2e87c5836d5e0b22793caf882e652d9529
https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/ccd99f2e87c5836d5e0b22793caf882e652d9529

😢 정반대로 바꾸는 것은 문제가 없었으나, 부호를 살리는 것과 다시 num type 으로 바꾸는 것에 대해서 어떻게 효율적으로 코드를 작성할 수 있을지 조금 고민을 했다.

😊 Math.sign()을 이용해 깔끔하게 부호를 살릴 수 있었고, Reverse String에서 쓰던 Skill들을 그대로 사용하였다.
그 외에 추가된 Skill은 toString(), parseInt()가 있다.

✔ Math.sign()

Math.sign()를 이용해 해당 변수의 부호를 알아내고 활용할 수 있다.
위의 소스코드에서 보면 알 수 있듯, arguments로 들어오는 n의 부호를 마지막에 곱해주어 해당 -(negative)를 다시 살려주었다.

✔ Number.prototype.toString()

처음에 들어오는 arguments가 number type이므로 reverse()를 이용할 것이라면 toString()으로 반드시 변환해줘야 한다.
그리고 reverse()를 사용하기 전에 split()사용하여 array로 반드시 변환해줘야 한다. Array.prototype.reverse()이기 때문이다.

✔ Global.parseInt()

string과 array를 이용해 number를 뒤바꾸어 주었으니, 최종값은 parseInt()를 이용해 number type으로 변환해야 한다.

Full Code

function reverseInt(n) {
let reversed = n
.toString()
.split('')
.reverse()
.join('');
return parseInt(reversed) * Math.sign(n);
}
 
// function reverseInt(n) {
// let rev = '';
 
// for (let num of n.toString()) {
// rev = num + rev;
// }
 
// return Math.sign(n) * parseInt(rev);
// }
 
// function reverseInt(n) {
// return (
// Math.sign(n) *
// parseInt(
// n
// .toString()
// .split('')
// .reduce((rev, num) => (rev = num + rev))
// )
// );
// }
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

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

+ Recent posts