728x90

https://www.acmicpc.net/problem/1712

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/37d399b654275b31f94815eb86c2853ec8cc5b1b/Baekjoon/1712.js

😢 21억 조건을 못 보고 반복문을 돌려 counter를 하나씩 증가시키려고 했다.. 잘못된 방법!

😊 역시나 수학 카테고리답게 다항식을 이용해서 풀면 쉽게 풀 수 있다.
A는 고정 비용, B는 가변 비용, C는 판매 가격이다.
판매 누적 금액고정비용+가변 누적 비용을 넘어서면 손익분기점을 넘어간다.
식을 만들어 본다면, A + Bx < Cx로 만들 수 있다. 
식을 정리해보자. A < Cx - Bx로 Bx를 넘겨주고, A < (C-B)x 로 정리해주면 조금 더 보기 쉽다.
즉, C-B가 0이하(즉, 0 또는 음수)로 떨어지면 손익분기점은 없다. 계속 적자다..ㅎㅎ

손익분기점이 없어서 '-1'을 출력하는 조건문은 2가지 정도로 표현할 수 있다.
1. if(C-B <= 0) { console.log(-1); }
A < (C-B)x 식을 생각해서 C-B가 0이하면 손익분기점은 없다고 표현할 수 있다.
2. if(C <= B) { console.log(-1); }
C-B > 0이 돼야하므로, C <= B으로 정리해주면 손익분기점이 없다고 표현할 수 있다.

Full Code

// Break-Even Point
 
// 1st Solution(other)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split(' ');
 
// For local test
const input = ['1000', '70', '170'];
const A = parseInt(input.shift());
const B = parseInt(input.shift());
const C = parseInt(input.shift());
const netProfit = C - B;
 
if (netProfit <= 0) {
console.log(-1);
} else {
console.log(Math.floor(A / netProfit) + 1);
}
 
// 2nd Solution(ohter)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split(' ').map(num => parseInt(num));
 
// For local test
// const input = ['1000', '70', '170'].map(num => parseInt(num));
// const A = input.shift();
// const B = input.shift();
// const C = input.shift();
 
// if (C <= B) {
// console.log(-1);
// } else {
// console.log(Math.floor(A / (C - B)) + 1);
// }
728x90

https://www.acmicpc.net/problem/1316

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/a283e8643975b13a658de279d66a7d2f989d9cab/Baekjoon/1316.js

😢 간단한 문제지만, 어떻게 하면 효율적으로 풀 수 있을까 고민했던 문제. 결과적으로 그다지 효과적이지 않은..

😊 결국 중첩 for loop을 이용해서 각 word의 문자를 체크하는 방법으로 풀었다.
Object를 하나 만들어주고, 해당 문자가 이미 사용되었다면 charMap에 '문자': true로 넣어주었다.
만약 charMap에 이미 해당 문자가 있다면 해당 word의 index-1과 같은지 비교해주었다.
같다면 그룹단어, 그렇지 않다면 더 이상 검사할 필요가 없기 때문에 counter를 감소시켜주고, break으로 내부 for loop을 끝냈다.

다른 정답자들의 풀이도 좋은 소스가 되었다.

Full Code

// Group Word Checker
 
// 3rd Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
// const input = ['3', 'happy', 'new', 'year'];
const input = ['4', 'aba', 'abab', 'abcabc', 'a'];
const N = parseInt(input.shift());
let counter = N;
 
for (let i = 0; i < N; i++) {
const charMap = {};
for (let j = 0; j < input[i].length; j++) {
if (!charMap[input[i][j]]) {
charMap[input[i][j]] = true;
} else if (input[i][j] !== input[i][j - 1]) {
counter--;
break;
}
}
}
 
console.log(counter);
 
// 1st Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
// const input = ['3', 'happy', 'new', 'year'];
// const input = ['4', 'aba', 'abab', 'abcabc', 'a'];
// const N = parseInt(input[0]);
// let counter = N;
 
// for (let i = 1; i <= N; i++) {
// const charMap = {};
// for (let j = 0; j < input[i].length; j++) {
// if (!charMap[input[i][j]]) {
// charMap[input[i][j]] = true;
// } else if (charMap[input[i][j]] && input[i][j - 1] === input[i][j]) {
// continue;
// } else {
// counter--;
// break;
// }
// }
// }
// console.log(counter);
 
// 2nd solution(other)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
// const input = ['3', 'happy', 'new', 'year'];
// const input = ['4', 'aba', 'abab', 'abcabc', 'a'];
// const N = parseInt(input.shift());
// let counter = 0;
 
// function checkGroupWord(str) {
// const checker = [];
 
// for (let i = 0; i < str.length; i++) {
// if (checker.indexOf(str[i]) === -1) {
// checker.push(str[i]);
// } else {
// if (checker[checker.length - 1] !== str[i]) {
// return;
// }
// }
// }
// counter++;
// }
 
// for (let i = 0; i < N; i++) {
// checkGroupWord(input[i]);
// }
 
// console.log(counter);
728x90

https://www.acmicpc.net/problem/2941

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/89a6bd743bd70a7b83988da93eca0436672e31e4/Baekjoon/2941.js

😢 단순 조건문 처리로는 풀기 싫어서, 어렵게 풀려다가 생각하는 시간이 조금 걸렸다.
그리고 문제를 보자마자 Regular Expression이 떠올라서, RegExp로 풀려고 공부를 조금 했다.

😊 조건문으로만 풀기에는 뭔가 문제가 아까웠다. 그래서 이런 방법 저런 방법을 시도해봤다. (물론 단순 조건으로도 풀어봤다)

regex변수크로아티아 알파벳 조건들을 입력해주고 replace() 에 주입하여, 만약 일치하는 것이 있다면 공백(' ')으로 만들어줬다.
RegExp 구성을 살펴보겠다. 아주 간단하다.
=, -와 같은 문자들은 특수문자이기 때문에 특별하다는 뜻으로 \(backslash, escape라고도 부른다)를 앞에 붙여줘야 하고,
그 외 조건들은 |(or)문자를 사용해서 구분해주었고, g를 붙여 Global search를 해줬다.

결과적으로 2개 이상 문자를 갖는 크로아티아 알파벳은 공백으로 변경되어 1개의 문자를 갖게 된다.
따라서 결과의 length를 출력해주면 크로아티아 알파벳의 개수를 알 수 있다.
(조건 외의 알파벳은 1개로 치니까 따로 처리하지 않는다)

Full Code단순 조건문 처리로 푼 예제도 있으니 참고하길 바란다.

✔ String.prototype.replce()

크로아티아 알파벳만의 조건을 넣어서, 공백(' ')으로 변경해주기 위해 사용했다.

✔ Regular Expressions

문자열을 다루기 위한 정규표현식이다. 크로아티아 알파벳 조건을 표현하기 위해 사용하였다.

위의 Skill들은 JavaScript - helper methods 카테고리에서 간단한 사용방법을 확인할 수 있다.

Full Code

// Croatia Alphabet
 
// 1st Solution(Regular Expressions)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
const input = 'ljes=njak';
 
var regex = /c\=|c\-|dz\=|d\-|lj|nj|s\=|z\=/g;
const result = input.replace(regex, ' ');
 
console.log(result.length);
 
// 2nd Solution(while, idx, if else)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = 'ljes=njak';
// let idx = 0;
// let counter = 0;
 
// while (idx < input.length) {
// if (
// input[idx] === 'c' &&
// (input[idx + 1] === '=' || input[idx + 1] === '-')
// ) {
// idx += 2;
// counter++;
// } else if (
// input[idx] === 'd' &&
// input[idx + 1] === 'z' &&
// input[idx + 2] === '='
// ) {
// idx += 3;
// counter++;
// } else if (input[idx] === 'd' && input[idx + 1] === '-') {
// idx += 2;
// counter++;
// } else if (
// input[idx + 1] === 'j' &&
// (input[idx] === 'l' || input[idx] === 'n')
// ) {
// idx += 2;
// counter++;
// } else if (input[idx] === 's' && input[idx + 1] === '=') {
// idx += 2;
// counter++;
// } else if (input[idx] === 'z' && input[idx + 1] === '=') {
// idx += 2;
// counter++;
// } else {
// idx++;
// counter++;
// }
// }
 
// console.log(counter);
 
// 3rd Solution(shift, while, if else)
 
// For submit
 
// const fs = require('fs');
// const str = fs.readFileSync('/dev/stdin').toString().trim().split('');
 
// For local test
// const str = 'ljes=njak'.split('');
// let counter = 0;
 
// while (str.length) {
// if (str[0] === 'c' && (str[1] === '=' || str[1] === '-')) {
// counter++;
// str.shift();
// str.shift();
// } else if (str[0] === 'd' && str[1] === 'z' && str[2] === '=') {
// counter++;
// str.shift();
// str.shift();
// str.shift();
// } else if (str[0] === 'd' && str[1] === '-') {
// counter++;
// str.shift();
// str.shift();
// } else if (str[1] === 'j' && (str[0] === 'l' || str[0] === 'n')) {
// counter++;
// str.shift();
// str.shift();
// } else if (str[0] === 's' && str[1] === '=') {
// counter++;
// str.shift();
// str.shift();
// } else if (str[0] === 'z' && str[1] === '=') {
// counter++;
// str.shift();
// str.shift();
// } else {
// counter++;
// str.shift();
// }
// }
 
// console.log(counter);
728x90

https://www.acmicpc.net/problem/5622

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/9c69b97d5fdc20167e9804bf0d73d8245c73732e/Baekjoon/5622.js

😢 알파벳을 직접 손으로 입력하고 싶지 않았고, Object로 value(각 지연 시간)까지 넣어서 진행하고 싶었다.
큰 어려움은 없었고, 중심을 Object로 만들고 푸는 과정에서 어떻게 진행할지 조금 고민했다.

😊 'A'부터 'Z'까지 진행하는 for loop을 열고, 'PQRS', 'WXYZ'는 예외로 들어가도록 조건문을 걸어주었다.
( i !== 'R'charCodeAt(0) && i !== 'Y'.charCodeAt(0) )으로 조건을 넣어준 이유는,
'PQRS', 'WXYZ' 이 2가지만 제외하면 모두 길이가 3이다. 그래서 길이 3으로 저장되기 전인 R or Y에서 저장을 차단하고,
앞의 두 문자가 각각 합쳐져 길이가 4가 되었을 때 key로 저장되도록 했다.

Object를 만들어준 후에, 입력 받고 split('')한 값에 reduce달았고, 안에 Object를 반복하는 for ... in loop을 열어주었다.
그렇게 입력받은 값 중각 key에 해당하는 문자가 있다면, acc에 해당 key의 value를 중복 저장해주고 return 해주었다.
결과적으로 result값에 전화를 걸기 위해 필요한 시간이 저장된다.

다른 풀이도 확인해보았지만, 대부분 직접 알파벳을 입력해서 사용하였고, 특별히 다른 점을 찾지 못 했다.

✔ Object {}

{ 'ABC' : 3, 'DEF': 4 ... } 이런 식으로 전체 알파벳을 저장하기 위해 작성하였다.

✔ charCodeAt()

해당 알파벳의 ASCII Code(숫자)를 알아내서 for loop을 이용하기 위해 사용하였다.

✔ String.fromCharCode()

()안에 ASCII코드를 넣어서 문자를 가져오기 위해 사용하였다.

✔ reduce

전화를 걸기 위해 필요한 시간을 중복 저장하기 위해 사용하였다.

✔ for ... in

Object의 key을 가져오는 for loop을 이용하기 위해 사용하였다.

위의 Skill들은 JavaScript - Helper methods or Grammar 카테고리에서 간단한 사용방법을 확인할 수 있다.

Full Code

// 2nd Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
const input = 'UNUCIC';
const splitInput = input.split('');
const charMap = {};
let charStack = '';
let counter = 3;
 
for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
charStack += String.fromCharCode(i);
 
if (
charStack.length === 3 &&
i !== 'R'.charCodeAt(0) &&
i !== 'Y'.charCodeAt(0)
) {
charMap[charStack] = counter;
counter++;
charStack = '';
} else if (charStack.length === 4) {
charMap[charStack] = counter;
counter++;
charStack = '';
}
}
 
const result = splitInput.reduce((acc, char) => {
for (let stage in charMap) {
if (stage.includes(char)) {
acc += charMap[stage];
}
}
return acc;
}, 0);
 
console.log(result);
 
// 1st Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = 'UNUCIC';
// const splitInput = input.split('');
// const charMap = {};
// let charStack = '';
// let counter = 3;
 
// for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
// charStack += String.fromCharCode(i);
 
// if (
// charStack.length === 3 &&
// i !== 'R'.charCodeAt(0) &&
// i !== 'Y'.charCodeAt(0)
// ) {
// charMap[charStack] = counter;
// counter++;
// charStack = '';
// } else if (charStack.length === 4) {
// charMap[charStack] = counter;
// counter++;
// charStack = '';
// }
// }
 
// let eachTime = 0;
// const result = splitInput.map(char => {
// for (let stage in charMap) {
// if (stage.includes(char)) {
// eachTime += charMap[stage];
// }
// }
// return eachTime;
// });
 
// console.log(result[result.length - 1]);
728x90

https://www.acmicpc.net/problem/2908

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/ebb4130f5a91e299f73bbe1e4e6d7986538d6e2b/Baekjoon/2908.js

😢 순서를 뒤바꾸는 방법으로 간단하게 푼 문제(Reverse Int or String Algorithm 참고)

😊 입력값으로 받은 숫자 StringArray로 나누고(split('')) reduce를 이용하여 순서를 뒤바꿔 줬다.
그런 후 각 세자리 숫자만큼 나눠서(split(' ')) 배열에 저장하고 Math.max.apply()를 이용해 더 큰 값을 구해줬다.
(아래 Full Code를 참고하면, reduce를 쓰지않고 다른 방법을 사용하여 푼 예제를 볼 수 있다)

✔ String.prototype.split('')

element 하나하나씩 나눠서 배열로 return해줬다. ( [ '7', '3', '4', ' ', '8', '9', '3' ] )

✔ Array.prototype.reduce()

안에 순서를 뒤바꾸는 reduce function을 주입하여 return해줬다. ( '398 437' )

✔ String.prototype.Split(' ')

가운데 공백(space)을 이용해 세자리 숫자씩 각각 나눠줬다. ( [ '734', '839' ] )

✔ Math.max.apply()

apply()에 숫자를 넣어서 max(더 큰)값을 구해줬다

위의 Skill들은 JavaScript - helper methods 카테고리에서 간단한 사용방법을 확인할 수 있다.

Full Code

// 2nd Solution(reduce(), Math.max.apply())
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
const input = '734 893';
const revEntire = input.split('').reduce((rev, numChar) => numChar + rev, '');
const eachNumArr = revEntire.split(' ');
const max = Math.max.apply(null, eachNumArr);
 
console.log(max);
 
// 1st Solution(reduce, Math.max.apply())
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = '734 893';
// const reverseInt = input
// .split('')
// .reduce((rev, num) => {
// return num + rev;
// }, '')
// .split(' ');
// const max = Math.max.apply(null, reverseInt);
 
// console.log(max);
 
// 3rd Solution(for...of, No Math.max())
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = '734 893';
// let rev = '';
 
// for (let numChar of input) {
// rev = numChar + rev;
// }
 
// const eachNumArr = rev.split(' ').map(num => parseInt(num));
// let max = 0;
 
// for (let i = 0; i < eachNumArr.length; i++) {
// if (eachNumArr[i] > max) {
// max = eachNumArr[i];
// }
// }
 
// console.log(max);
 
// 4th Solution(reverse())
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = '734 893';
// let rev = input
// .split('')
// .reverse()
// .join('');
 
// const eachNumArr = rev.split(' ').map(num => parseInt(num));
// let max = 0;
 
// for (let i = 0; i < eachNumArr.length; i++) {
// if (eachNumArr[i] > max) {
// max = eachNumArr[i];
// }
// }
 
// console.log(max);
728x90

https://www.acmicpc.net/problem/1157

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/123b9d1a5e69e84767efb10bce4bf7d50614da45/Baekjoon/1157.js

😢 '?'를 출력하는 조건 때문에 조금 고민한 문제.
Max Chars Algorithm(가장 많이 쓰인 문자 찾기 알고리즘)이랑 비슷한데 조금 달랐다.
그래서 Max Chars에서 사용한 스킬을 접목시켜보고 싶었다.

😊 먼저, charMap Object를 만들어주고, for ... of를 사용해서 각 문자가 쓰인 만큼 Object에 저장해주었다.
(key문자, value쓰인 개수)
max를 구하는 방법은 Math.max.apply를 이용해서 다르게 구해주었다.
for loop을 한 번 더 쓰고싶지 않았기 때문이다.(쓴 것과 속도는 비슷할듯)

다시 for ... in 을 열어주고, 미리 구한 max같은 것이 있다면 counter를 증가시켜줬다.
만약 counter가 1개만 증가했다면, 가장 많이 쓰인 문자는 1개인 것이고, 1개가 넘는다면 같은 max가 존재한다는 것!
결과적으로, 만약 counter > 1이라면 '?'를 출력하고 return, 아니라면 maxChar(가장 많이 쓰인 문자)를 출력해주었다.

다른 사람들이 푼 것도 살펴봤지만, 풀이 방법은 비슷하고, 가독성이 좋은 코드가 없어서 그냥 보기만 했다.(속도는 빨랐다)
내 코드가 가독성은 더 좋다고 생각하는데, 아마 Object, Ternary, for ... of, for ...in 그리고 Object.values를 모른다면 어려울 것 같긴 하다. 위의 개념은 JavaScript - helper methods or Grammar 카테고리에서 간단한 사용방법을 볼 수 있다.

✔ Object {}

charMap = { 'a': 1, 'b': 3 }; 이렇게 저장된다고 생각하면 된다.

✔ Ternary(삼항 조건 연산자)

charMap[char] = charMap[char] ? charMap[char]+1 : 1;
charMap[char]이 있다면 +1, 없다면 1을 넣어준다는 뜻이다.

✔ for ... of

classic for loop과 같지만, index범위를 지정하는 것이 없고, 알아서 값을 하나씩 가져온다고 생각하면 된다.
array-like를 사용할 때 이용 가능하다.

✔ for ... in

위의 for of와 같지만, Object의 for loop을 사용하기 위해 쓰는 문법이다.

✔ Object.values()

{ 'a': 1, 'b': 3 } 이라는 Object가 있을 때, [ 1, 3 ]처럼 values만 뽑아준다.

위의 Skill들은 JavaScript - helper methods or Grammar 카테고리에서 간단한 사용방법을 볼 수 있다.

Full Code

// 2nd Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
const input = 'Mississipi';
const charMap = {};
 
for (let char of input.toLowerCase()) {
charMap[char] = charMap[char] ? charMap[char] + 1 : 1;
}
 
let max = Math.max.apply(null, Object.values(charMap));
let maxChar = '';
let counter = 0;
for (let char in charMap) {
if (charMap[char] === max) {
maxChar = char;
counter++;
}
if (counter > 1) {
console.log('?');
return;
}
}
 
console.log(maxChar.toUpperCase());
 
// 1st Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = 'Mississipi';
// const newStr = input.toLowerCase();
// const charMap = {};
 
// for (let char of newStr) {
// charMap[char] = charMap[char] ? charMap[char] + 1 : 1;
// }
 
// let max = 0;
// for (let char in charMap) {
// if (charMap[char] > max) {
// max = charMap[char];
// maxChar = char.toUpperCase();
// }
// }
 
// let counter = 0;
// for (let char in charMap) {
// if (charMap[char] === max) {
// counter++;
// }
// if (counter > 1) {
// console.log('?');
// return;
// }
// }
 
// console.log(maxChar);
728x90

https://www.acmicpc.net/problem/2675

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/40b59357968466b842f18f3246d2964883b97c86/Baekjoon/2675.js

😢 긴가민가? 하면서 계속 진행하며 풀어봤더니 해결된 문제. 문자열은 역시 배열 index를 잘 다뤄야 좋다(문자열도 배열이니까)

😊 T에 Test Case 수를 저장하고, 그 수만큼 반복되는 for loop을 열어준다.
반복할 수인 R을 따로 저장해주고, 반복될 문자열 S도 따로 저장해주는데, 특히 S는 배열 String에서 그냥 String으로 변환해준다.
( 처음에 입력값을 가져올 때 R과 S는 함께 있으므로, split(' ') 후 slice를 이용해 잘라준다)
마지막으로, 문자열의 길이 S만큼 반복하는 for loop안에 반복할 수 R만큼 반복하는 for loop을 열어줘서 같은 문자를 P에 중복 대입해준다. 한 문장이 끝날 때마다 console.log(P);를 통해 출력해주면 된다.

✔ parseInt()

String을 Number로 변환해주기 위해 사용하였다.
(자세한 내용은 JavaScript-helper method 카테고리에 있다)

✔ split(' ')

R과 S를 분리하기 위해 사용하였다.
(자세한 내용은 JavaScript-helper method 카테고리에 있다)

✔ slice()

R은 index 0, S는 index 1에 있으므로, slice를 이용해 잘라서 저장해준다.
(자세한 내용은 JavaScript-helper method 카테고리에 있다)

Full Code

// Repeat String
 
// 2nd Solution(Understandable code)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
const input = ['2', '3 ABC', '5 /HTP'];
const T = parseInt(input[0]);
 
for (let i = 1; i <= T; i++) {
const R = parseInt(input[i].split(' ').slice(0));
const S = input[i]
.split(' ')
.slice(1)
.toString();
let P = '';
 
for (let j = 0; j < S.length; j++) {
for (let k = 0; k < R; k++) {
P += S[j];
}
}
console.log(P);
}
 
// 1st Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
// const input = ['2', '3 ABC', '5 /HTP'];
// const T = parseInt(input[0]);
 
// for (let i = 1; i <= T; i++) {
// const testCase = input[i].split(' ');
// const R = parseInt(testCase[0]);
// let result = '';
// for (let j = 0; j < testCase[1].length; j++) {
// for (let k = 0; k < R; k++) {
// result += testCase[1][j];
// }
// }
// console.log(result);
// }
728x90

https://www.acmicpc.net/problem/10809

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/32a64dbe8893d8f448507bb4900a155eb54a5764

😢 C언어로 자주 알파벳 가지고 놀았었는데, 기억이 잘 나지 않아서 검색을 좀 했다.
JavaScript로 ASCII Code 다루는 방법을 익혀서 새로웠지만 재밌었다.

😊 Solution 1)
단순하게 한 번 풀어보고자, 모든 알파벳을 배열에 담고 비교해보았다. for ... of를 이용해서 알파벳을 하나씩 반복해주고,
if else를 이용해서 해당 알파벳이 있다면 index를, 없다면 -1를 배열로 저장하였다. 출력은 join(' ')으로 형식을 맞춰주면 된다.


Solution 2)
먼저, 결과값을 담아줄 result array를 선언하였다. 그리고
for loop의 범위로 a-z를 주었다. 'a'는 ASCII Code 97번이고, 'z'는 ASCII Code 122번이기 때문에 97-122까지 반복 실행된다.
입력된 문자열(input 변수)에 해당하는 알파벳이 있다면 그 값의 index를, 없다면 -1를 반환하여 result array에 저장한다.
마지막으로, join(' ')을 통해 출력 형식을 맞춰 주면 된다.

가장 중요한 것-1 또는 해당 index라는 키워드가 나왔을 때, indexOf를 떠올릴 수 있어야 한다.

✔ String.prototype.charCodeAt()

각 알파벳의 ASCII Code를 알아내기 위해 사용하였다.
JavaScript-helper method에서 예제를 다뤄 보겠다.

✔ String.fromCharCode()

해당 ASCII Code에 해당하는 문자를 반환한다.
indexOf안에 찾고자하는 character를 넣기 위해 사용했다.(a-z의 ASCII Code가 순서대로 들어간다)
JavaScript-helper method에서 예제를 다뤄 보겠다.

✔ String.prototype.indexOf()

입력받은 값중에 해당 알파벳이 있는지, 있다면 그 위치(index)를 반환받고, 없다면 -1을 반환받기 위해 사용하였다.
JavaScript-helper method에서 예제를 다뤄 보겠다.

Full Code

// 2nd Solution
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString();
 
const input = 'baekjoon';
const result = [];
 
for (let i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) {
result.push(input.indexOf(String.fromCharCode(i)));
}
 
console.log(result.join(' '));
 
// 1st Solution(not so good)
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// const input = ['baekjoon'];
// const checker = [
// 'a',
// 'b',
// 'c',
// 'd',
// 'e',
// 'f',
// 'g',
// 'h',
// 'i',
// 'j',
// 'k',
// 'l',
// 'm',
// 'n',
// 'o',
// 'p',
// 'q',
// 'r',
// 's',
// 't',
// 'u',
// 'v',
// 'w',
// 'x',
// 'y',
// 'z'
// ];
 
// const result = [];
 
// for (let char of checker) {
// if (input[0].includes(char)) {
// result.push(input[0].indexOf(char));
// } else {
// result.push(-1);
// }
// }
 
// console.log(result.join(' '));
728x90

https://www.acmicpc.net/problem/11720

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/78e0013ef4cd58297d7eb5ce9e55a6d8799a179a

😢 보자마자 바로 풀 수 있었다. 매우 기초적인 문제.

😊 for ... of 를 이용하여 하나씩 더해 주거나, classic for loop을 이용해서 하나씩 더해 주면 된다.

✔ for ... of

array 값을 순서대로 하나씩 가져오며, array의 길이만큼 반복해준다.

✔ 2차원 배열(Two-dementional Array)

입력값을 문자열로 가져오기 때문에 배열로 값을 지정하여 가져올 수 있다.
(e.g., input = [ '5', '54321' ]; 이라면 input[1]의 '5'는 input[1][0])

Full Code

// For Submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For Local Test
let input = ['5', '54321'];
let sum = 0;
 
// 1st Solution
 
for (let num of input[1]) {
sum += parseInt(num);
}
 
console.log(sum);
 
// 2nd Solution
 
// for (let i = 0; i < parseInt(input[0]); i++) {
// sum += parseInt(input[1][i]);
// }
 
// console.log(sum);
728x90

Q. 정수 n을 입력받아, Fibonacci(피보나치 수열)의 n번째 수를 출력하라.

피보나치 수열이란 처음 두 항을 1과 1로 한 후, 그 다음 항부터는 바로 앞의 두 개의 항을 더해 만드는수열을 말한다.

For example, the sequence
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
forms the first ten entries of the fibonacci series.
Example:
fib(4) === 3

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/53f67dc993aafda9352612d93aba066634d945c8/exercises/fib/index.js

😢 배열을 이용한 단순 fib는 쉽게 풀었고, recursion(재귀)를 사용하는 fib는 생각하기에는 어려웠지만 단순했고, memoize(Dynamic Programming)은 매우 생소해서 익숙해지는 시간이 필요했다.

😊 Solution 1)
index 0과 1의 값을 미리 저장한 배열(array)를 선언해주고, classic for loop을 반복해주었다.
i는 1부터 시작해주고 arr.push(arr[i-1] + arr[i-2])형식으로 index를 조정해주어 값을 push해주고 arr[n]을 출력해주면 된다.

Solution 2) 재귀함수(Recursion)
재귀함수를 이용한다.
만약 n값이 2보다 작다면 n값을 return하는 Base Case를 걸어두어 간단하게 해결할 수 있다.
(무조건 index 0은 0이고, index 1은 1로 시작하기 때문이며, 최대 -2를 해주므로, 0또는 1값만 발생할 수 있다)
0, 1, 1이 합쳐져 다음 수를 만들고, 이것들이 결과적으로 피보나치 수열을 이루기 때문이다(결국 1을 찾는 것이다)
return fib(n-1) + fib(n-2);을 통해 처음부터 끝까지 모든 경우의 수를 재귀적으로 실행한다.

모든 경우의 수를 탐색하는 재귀적 피보나치 수열 그래프

Solution 3) 재귀함수와 Memoize(Dynamic Programing)
재귀함수로 검색을 해주지만, 모든 경우의 수를 탐색하지 않고, cache를 생성하여 한 번 검색한 값은 저장하고, 다시 탐색하지 않는다.
재귀함수 fib(여기서는 slowFib)를 memoize함수 안에서 실행하도록 하여, 한 번 탐색한 값은 cache object에 저장하고 그 값을 다시 탐색한다면 cache에서 값을 꺼내 반환해준다. 만약 처음으로 탐색하는 값이라면 slowFib를 실행시킨다.
이렇게 재귀함수를 사용해주면 시간낭비 없이 효율적으로 재귀를 진행할 수 있다.

✔ Nested functions

Memoize function안에 inner function을 만들어줘서, 이미 검색한 값이라면 cache[args]를 리턴, 그게 아니라면 검색하게 한다.
이 과정을 통해 시간 복잡도를 줄일 수 있다. 검색하는 시간을 줄여주기 때문이다.
JavaScript - Grammar 카테고리에서 조금 더 다뤄 보겠다.

✔ Function.prototype.apply()

memoize의 inner function에서 slowFib를 실행시켜주는 방법이다.
helper method 카테고리에서 조금 더 다뤄 보겠다.

✔ this

이 문제에서는 사실 apply()의 첫 번째 parameter에 null or this를 넣어도 큰 상관은 없지만,  this로 넣어줬다.
간단히 말하자면 this는 자신의 왼쪽(소속)을 나타낸다.
 JavaScript - Grammar에서 조금 더 다뤄 보겠다.

✔ args(The arguments object)

입력값을 간접적으로(?) 넘겨주기 위해 사용했다.
function안에서 다룰 수 있는 Array-like object인 arguments이며,
JavaScript - Grammar에서 조금 더 다뤄 보겠다.

✔ ... (Spread)

args를 array처럼 만들어 줄 수 있다. apply()의 두 번째 parameter가 array이므로 array-like값을 넘어주기 위해 사용했다.
JavaScript - ES2015 카테고리에서 개념을 확인할 수 있다.

Full Code

function memoize(fn) {
const cache = {};
return function(...args) {
if (cache[args]) {
return cache[args];
}
 
const result = fn.apply(this, args);
cache[args] = result;
 
return result;
};
}
 
function slowFib(n) {
if (n < 2) {
return n;
}
 
return fib(n - 1) + fib(n - 2);
}
 
const fib = memoize(slowFib);
 
// function fib(n) {
// const result = [0, 1];
 
// for (let i = 2; i <= n; i++) {
// const a = result[i - 2]; // === result[result.length -2];
// const b = result[i - 1]; // === result[result.length -1];
 
// result.push(a + b);
// }
 
// return result[n]; // === result[result.length -1];
// }
 
// function fib(n) {
// if (n < 2) {
// return n;
// }
 
// return fib(n - 1) + fib(n - 2);
// }

+ Recent posts