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');
// }

+ Recent posts