오늘 풀 문제는 가지고 있는 N개의 종류의 동전으로 K원을 만드는데
필요한 최소한의 동전 개수를 구하는 것이다.


let input = require("fs")
.readFileSync("input.txt")
.toString()
.trim()
.split("\\n");
let coin = 0;
let total = parseInt(input[0].split(" ")[1]);
let money = {
one: parseInt(input[1]),
five: parseInt(input[2]),
ten: parseInt(input[3]),
fifty: parseInt(input[4]),
hundred: parseInt(input[5]),
fivehundred: parseInt(input[6]),
thousand: parseInt(input[7]),
fivethousand: parseInt(input[8]),
tenthousand: parseInt(input[9]),
fiftythousand: parseInt(input[10]),
};
while (total > 0) {
if (total >= money.fiftythousand) {
coin += Math.floor(total / money.fiftythousand);
total = Math.floor(total % money.fiftythousand);
} else if (total >= money.tenthousand) {
coin += Math.floor(total / money.tenthousand);
total = Math.floor(total % money.tenthousand);
} else if (total >= money.fivethousand) {
coin += Math.floor(total / money.fivethousand);
total = Math.floor(total % money.fivethousand);
} else if (total >= money.thousand) {
coin += Math.floor(total / money.thousand);
total = Math.floor(total % money.thousand);
} else if (total >= money.fivehundred) {
coin += Math.floor(total / money.fivehundred);
total = Math.floor(total % money.fivehundred);
} else if (total >= money.hundred) {
coin += Math.floor(total / money.hundred);
total = Math.floor(total % money.hundred);
} else if (total >= money.fifty) {
coin += Math.floor(total / money.fifty);
total = Math.floor(total % money.fifty);
} else if (total >= money.ten) {
coin += Math.floor(total / money.ten);
total = Math.floor(total % money.ten);
} else if (total >= money.five) {
coin += Math.floor(total / money.five);
total = Math.floor(total % money.five);
} else if (total >= money.one) {
coin += Math.floor(total / money.one);
total = Math.floor(total % money.one);
}
}
console.log(coin);
우선 나는 위와 같이 풀었는데 기본 원리는 어렵지 않아서 짧은 시간 내에 풀 수 있었다.
가지고 있는 동전 중 가장 값이 큰 동전부터 비교해서 나눌 수 있는 구간에 나누기를 하도록 만들었고
나눈 몫은 동전의 개수에 추가하고 나눈 나머지는 총액의 값으로 변경해주었다.
그리고 입력받을 때 모두 String으로 받았기 때문에 Int 형태로 변환하는 작업을 추가했다.
하지만 나는 이 코드가 매우 맘에 들지 않는다.
그래서 이러한 문제점을 해결하기 위해 저 코드를 더 나은 방식으로 구현할 수 있도록 고민중이다.
let input = require("fs")
.readFileSync("input.txt")
.toString()
.trim()
.split("\\n");
let coin = 0;
let category = parseInt(input[0].split(" ")[0]);
let total = parseInt(input[0].split(" ")[1]);
let money = [];
for (let i = 0; i < category; i++) {
money[i] = parseInt(input[i + 1]);
}
for (let i = category - 1; i >= 0; i--) {
coin += Math.floor(total / money[i]);
total = total % money[i];
}
console.log(coin);
짜잔! 이렇게 고쳤다.