728x90

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

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/54592b15a8664302e6d2c812440edabf9b417013

😢 5분 정도 고민하고, 코드로 하나씩 정리해 나가면서 금방 풀 수 있었던 문제

😊 전체 Test Case를 반복할 수 있는 for loop을 가장 바깥에서 돌리고, 중첩 첫 번째 for loop에서 점수를 모두 더해준 후 평균을 구한다. 그리고 중첩 두 번째 for loop에서 평균보다 높은 인원수를 구하고 비율을 계산해주고 출력한다.
평균을 어떻게 구할지, 평균을 넘는 인원은 몇명인지, 비율을 구하는 공식은 무엇인지 먼저 정리하고 풀어나가면 금방 해결할 수 있다.

Full Code

// 1st Solution
 
// For submit
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
const input = [
'5',
'5 50 50 70 80 100',
'7 100 95 90 80 70 60 50',
'3 70 90 80',
'3 70 90 81',
'9 100 99 98 97 96 95 94 93 91'
];
 
const C = parseInt(input[0]);
 
for (let i = 1; i <= C; i++) {
const NAndGradeArr = input[i].trim().split(' ');
let totalGrade = 0;
let avg = 0;
let counter = 0;
let proportion = 0;
for (let j = 1; j <= parseInt(NAndGradeArr[0]); j++) {
totalGrade += parseInt(NAndGradeArr[j]);
}
 
avg = totalGrade / parseInt(NAndGradeArr[0]);
 
for (let k = 1; k <= parseInt(NAndGradeArr[0]); k++) {
if (parseInt(NAndGradeArr[k]) > avg) {
counter++;
}
}
 
proportion = (counter / parseInt(NAndGradeArr[0])) * 100;
console.log(proportion.toFixed(3) + '%');
}
// 비율 구하는 공식 : 비교량 / 기준량 * 100 (2 / 5 * 100)
 
// other solution (좀 특이해서 참고해보았다)
 
// var a = require('fs')
// .readFileSync('/dev/stdin')
// .toString()
// .match(/[^\r\n]+/g)
// .slice(1),
// b = a.map(function(x) {
// return x.split(' ');
// }),
// c = [],
// e = [];
// for (var i = 0; i <= b.length - 1; i++) {
// c.push(
// b[i].reduce(function(pre, cur) {
// return parseInt(pre) + parseInt(cur);
// }) /
// b[i][0] -
// 1
// );
 
// e.push(
// b[i].slice(1).filter(function(x) {
// return x > c[i];
// })
// );
 
// console.log(((e[i].length / b[i][0]) * 100).toFixed(3) + '%');
// }
728x90

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

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/f1fa3910361f1978f2443cba1df1b851b055da38

😢 이번 문제는 꽤나 고민을 했다. 첫 풀이 때는, 중첩 for loop을 2번이나 써서 '1. 점수를 얻어내고 2. 점수를 계산하여' 출력 하였다. 
하지만 2번째 풀이에서(위의 코드)는 중첩 for loop 한 번으로 점수를 얻음과 동시에 출력하였다. 중첩 for loop을 한 개나 없앴다는 것에 만족한다. 대략 30분 정도 걸렸던 것 같다. 혼자 못 풀 문제는 아니었다.

😊 첫 번째 for {}안에 점수를 표시할 counter와 점수를 더할 eachSum을 선언하였다. 그리고 두 번째 for {}안에서 배열의 해당 index가 O라면 counter를 증가하며 eachSum에 계속 더하였고, X라면 counter가 다시 1로 시작하도록 초기화하였다.
두 번째 for {}이 끝난 후 한 줄의 OX점수를 합한 eachSum을 출력해주었다.

Full Code

 

// 1st Solution (submitted)
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
 
const input = [
'5',
'OOXXOXXOOO',
'OOXXOOXXOO',
'OXOXOXOXOXOXOX',
'OOOOOOOOOO',
'OOOOXOOOOXOOOOX'
];
 
// 2nd Solution
 
const N = parseInt(input[0]);
 
for (let i = 1; i <= N; i++) {
let counter = 1;
let eachSum = 0;
for (let j = 0; j < input[i].length; j++) {
if (input[i][j] === 'O') {
eachSum += counter;
counter++;
} else {
counter = 1;
}
}
console.log(eachSum);
}
 
// 1st Solution
 
// const N = parseInt(input[0]);
// const result = [];
// let idx = 0;
 
// for (let i = 1; i <= N; i++) {
// let counter = 0;
// for (let j = 0; j < input[i].length; j++) {
// if (input[i][j] === 'O') {
// counter++;
// result.push(counter);
// } else {
// counter = 0;
// result.push(counter);
// }
// }
// }
 
// for (let i = 1; i <= N; i++) {
// let eachSum = 0;
// for (let j = 0; j < input[i].length; j++) {
// eachSum += result[idx];
// idx++;
// }
// console.log(eachSum);
// }
 
// other solution
 
// const N = parseInt(input[0]);
 
// for (let i = 0; i < N; i++) {
// let eachO = String(input[i + 1]).split('X');
// let sum = 0;
// for (let j = 0; j < eachO.length; j++) {
// for (let k = 1; k <= String(eachO[j]).length; k++) {
// sum += k;
// }
// }
// console.log(sum);
// }
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);
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