Answer the question
In order to leave comments, you need to log in
How to solve a problem with enumeration?
The task is as follows:
"There is a certain fixed number of coins with denominations of 2,3,5. It is necessary to create an algorithm of actions that is guaranteed to check the possibility of obtaining a given number by summing the available coins."
I thought to solve it through a dynamic array and recursion, but so far I'm not good at it. Maybe there is another better solution
Answer the question
In order to leave comments, you need to log in
The easiest solution to understand is a complete search. Stupidly 3 cycles - how many coins with a face value of 2 were taken, how many coins with a face value of 3 and how many coins with a face value of 5. Each cycle from 0 to <How much to collect> / face value. Then we check that the sum has converged. Moreover, you can skip the last cycle and just check that the rest can be scored with nickels.
bool CanExchange(int n, int have2, int have3, int have5) {
for(int take2 = 0; take2 <= min(have2, n/2); ++take2) {
int left2 = n - 2*take2;
for (int take3 = 0; take3 < min(have3, left2/3); ++take3) {
int left23 = left2 - take3*3;
if (left23 % 5 == 0 && left23 / 5 <= have5) {
return true;
}
}
}
return false;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question