Search code examples
calgorithmcoin-change

I'm coding a brute-force algorithm on change making and I'm a little stuck


I need to write a program that uses brute-force method to find out how to make change the most efficiently. I'm a little confused and I'm curious if I'm on the right track. I'm writing it in C.

It does not use a greedy algorithm.

It's just confusing me is all. In the end it should output the most efficient change as toonie, loonie, quarter, dimes, nickels, pennies, in that order. (Like 1 1 0 0 1 0.)

Am I on the right track? I'm a little confused as to what I'm doing, six for loops is apparently the key, and I'm adding each iteration, but as to what's going on conceptually I'm a little confused.

#include <stdio.h>

int main(int argc, char *argv[]) {
    //Input
    int amount = 336;
    int bestSolution = amount;
    //Coins
    int toonies = 0, loonies = 0, quarters = 0, dimes = 0, nickels = 0, pennies = 0;
    int amountAfterToonies, amountAfterLoonies, amountAfterQuarters, amountAfterDimes, amountAfterNickels;
    //Counters
    int i, j, k, l, m, n;

    for (i = 0; i < amount / 200; i++) { //Finds amount 
        toonies++;
        amountAfterToonies = amount % 200;
        for (j = 0; j < amountAfterToonies / 100; j++) {
            loonies++;
            amountAfterLoonies = amountAfterToonies % 100;
            for (k = 0; k < amountAfterLoonies / 25; k++) {
                quarters++;
                amountAfterQuarters = amountAfterLoonies % 25;
                for (l = 0; l < amountAfterQuarters / 10; l++) {
                    dimes++;
                    amountAfterDimes = amountAfterQuarters % 10;
                    for (m = 0; m < amountAfterDimes / 5; m++) {
                        nickels++;
                        amountAfterNickels = amountAfterDimes % 5;
                    for (n = 0; n < amountAfterNickels; n++) {
                        pennies++;
                        sum = toonies + loonies + quarters + dimes + nickels + pennies;
                        if (sum < bestSolution) {
                            bestSolution = sum;
                        }
                    }
                }
            }
        }
    }
}
printf("%d %d %d %d %d %d\n", toonies, loonies, quarters, dimes, nickels, pennies);
printf("%d\n", bestSolution);
return 0;
}

Solution

  • You don't find most efficiently way. You find all ways.

    I suggest you something like:

    toonies=amount/200;
    amount%=200;
    loonies=amount/100;
    amount%=100;
    //and so on
    

    (Even if you want to keep the loops, separate them - there is no reason to use nested loops)