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