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

✨ array의 마지막 값을 제거하고, 제거된 값을 반환한다.
(기존 array가 제거된 상태로 갱신된다)

💻Example Code

const arr = [ 'apple', 'juice', 'flower' ];

console.log( arr.pop() );
console.log( arr );

실행 결과(마지막 값인 flower 반환, 새로운 array 갱신)

😋 큐(Queue) 자료구조(Data Structure)의 remove()에서 사용할 수 있으며, 그 외에도 pop()은 정말 많은 곳에 쓰인다.
array에서 아예 제거된다는 것을 명심하자.
(큐 자료구조는 JavaScript - Data Structures에서 확인 가능하다)

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

 

Array.prototype.pop()

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

developer.mozilla.org

 

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

Array.prototype.map()  (0) 2020.01.11
Array.prototype.push()  (0) 2020.01.06
Array.prototype.unshift()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
728x90

✨ 배열(array)의 가장 앞에 값을 넣어주고, 새로운 array의 길이를 반환하는 helper method
(Queue와 같이 First In이 필요한 상황에서 사용할 수 있다)

💻Example Code

const arr = [ 3, 4 ];
arr.unshift(1, 2);

console.log( arr );

실행 결과(기존 3, 4 앞에 1, 2가 삽입된 것을 볼 수 있다)

😋 큐(Queue) 자료구조(Data Structure)처럼 항상 값이 가장 앞에 들어가야하는 경우 사용할 수 있다.
큐 자료구조는 JavaScript - Data Structures에서 확인할 수 있다.

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

 

Array.prototype.unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

developer.mozilla.org

 

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

Array.prototype.push()  (0) 2020.01.06
Array.prototype.pop()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
728x90

Q. 값을 다르게 가지고 있는 2개의 큐(Queue)를 1개의 큐(Queue)로 만드는 weave 함수(function)을 만들어라.
(단, 값을 번갈아 넣어야하며, undefined는 없어야 한다.
또한, 어떠한 array도 만들어서는 안 되며, Queue의 add, remove, peek method만 이용하여 작성해야한다)

정답 예시

🎈 먼저, 값이 많이 있기 때문에 반복 작업이 필요하다. 그러니 '반복문'을 먼저 떠올려야할 것이다.
그리고 undefined가 들어가면 안 되니, 값이 있는지를 확인하는 '조건문'이 있어야한다.

값이 있는지 확인하는 peek()반복문의 조건으로 넣을 수 있을 것이다. 값이 있다면 '반복'해야하니까.
그리고 또한 한쪽의 값이 먼저 다 소진될 수 있으니, 반복문 안에서도 값이 있는지 또 확인하는 조건문도 필요하다.

조건이 맞는다면 해당 큐에서 값을 제거한다. remove()
그리고 새로운 큐에 값을 넣어준다. add()

위처럼 간단하게 생각하고 시작하면 된다.

🔮 가장 먼저, 새로운 큐를 만들어줘야한다. const q = new Queue();
반복문의 조건while( srcOne.peek() || srcTwo.peek() )을 넣어 둘 중 하나의 큐에 값이 있다면 반복한다.
조건문 if ( srcOne.peek() )if ( srcTwo.peek() )을 넣어줘서, 둘 중 하나의 큐라도 값이 있다면 실행시킨다.
if의 내부에서는 q.add( srcOne.remove() )를 통해 기존 값을 새로운 큐(q)에 넣어준다.

이렇게 반복해주면 번갈아 값을 넣는 weave algorithm이 완성된다.

Weave Algorithm 정답

Full Code

function weave(sourceOne, sourceTwo) {
const q = new Queue();
 
while (sourceOne.peek() || sourceTwo.peek()) {
if (sourceOne.peek()) {
q.add(sourceOne.remove());
}
if (sourceTwo.peek()) {
q.add(sourceTwo.remove());
}
}
 
return q;
}
728x90

큐의 정의(Definition of Queue)

🎈 위 그림에서 볼 수 있듯, Queue의 실행 순서는 FIFO로 진행된다.
FIFO란 First In First Out의 약자로서, 처음 들어간 값이 가장 먼저 나올 수 있다. 선입선출이라고 생각하면 쉽다.

Queue는 기본적으로 추가( add() ), 삭제( remove() ) 기능을 사용하여 다루며,
마지막 값 보기( peek() ) 기능처럼 본인이 필요한 기능을 만들어 사용하면 된다.

JavaScript의 class를 이용하여 Queue를 만들어 보겠다.

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/d869a976ec23478534e899b54d7e2b9160698639/exercises/weave/queue.js

😐 위에서 볼 수 있듯, Queue의 전체 뼈대는 생성자(constructor)를 이용하여 array를 선언해준다.

Array의 helper method

add()에서는 Array.prototype.unshift()를 이용하여, 값이 항상 Queue의 앞으로 들어가게 구성해준다.

remove()에서는 Array.prototype.pop()를 이용하여, 항상 (먼저 들어간)마지막 값이 나올 수 있게 구성한다.

peek()에서는 index에 [this.data.length-1]을 넣어줘서 값이 있다면 마지막 값을, 없다면 undefined를 return하게 해준다.

🎉이렇게 class를 작성해주면, FIFO(First In First Out)기능을 하는 기본 Queue를 만들어낼 수 있다.

다음 글에서는 값이 다른 2개의 큐(Queue)를 1개의 큐(Queue)로 만들어보는 자료구조를 이용한 알고리즘에 대해 작성해보겠다.

Full Code

class Queue {
constructor() {
this.data = [];
}
 
add(record) {
this.data.unshift(record);
}
 
remove() {
return this.data.pop();
}
 
peek() {
return this.data[this.data.length - 1];
}
}
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

✨ASCII Code를 string으로 반환해주는 helper method

💻Example Code

console.log( String.fromCharCode(97) );
console.log( String.fromCharCode(113) );
console.log( String.fromCharCode(65) );

실행 결과(ASCII Code 97은 'a', 113은 'q', 65는 'A'라는 것을 알 수 있다)

😋 ASCII Code를 활용하는 문제를 풀 때 간혹 필요할 수 있다. ASCII Code를 string으로 바꿔준다.
백준 알파벳 찾기(Find alphabet) 알고리즘 문제를 풀 때 사용했다.

ASCII Code

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

 

String.fromCharCode()

The static String.fromCharCode() method returns a string created from the specified sequence of UTF-16 code units.

developer.mozilla.org

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

Array.prototype.pop()  (0) 2020.01.04
Array.prototype.unshift()  (0) 2020.01.04
Array.prototype.indexOf()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
String.charCodeAt()  (0) 2019.12.31
728x90

✨ 주어진 array에서 찾고자하는 element의 index를 반환, 없다면 -1을 반환하는 helper method
(index는 가장 먼저 발견된 element 기준으로 반환된다)

💻Example Code

const arr = 'gamgongsa';

console.log( arr.indexOf('a') );
console.log( arr.indexOf('g') );
console.log( arr.indexOf('z') );

실행 결과('a'의 index는 1, 'g'의 index는 0, 'z'는 없기 때문에 -1)

😋 긴 문자열이 주어지고, 여기서 내가 원하는 알파벳이 있는지 없는지를 확인하고자 할 때 쓰기 좋은 helper method
알파벳 찾기(Find alphabet) 알고리즘 문제를 풀 때 사용했다.

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

 

Array.prototype.indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

developer.mozilla.org

 

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

Array.prototype.unshift()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
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);

+ Recent posts