a thoughtful web.
Good ideas and conversation. No ads, no tracking.   Login or Take a Tour!
comment
briandmyers  ·  3373 days ago  ·  link  ·    ·  parent  ·  post: A nice problem from SICP

I banged out a brute-force iterative solution pretty quickly in C.

It's not general, but could be made so pretty easily.

  #include <stdio.h>

#define NUM_COINS 5

#define GOAL_IN_CENTS 100

unsigned char ucCoinVal[] = { 1, 5, 10, 25, 50 };

unsigned char isGoodSet( unsigned char aucCoins[] );

int main( void )

{

int i;

unsigned char max[NUM_COINS];

unsigned char aucCoins[NUM_COINS];

int iTotal = 0;

for ( i = 0; i < NUM_COINS; i++ )

{

max[i] = GOAL_IN_CENTS / ucCoinVal[i];

printf( "\nCoin %3d cents has max %3d for goal", ucCoinVal[i], max[i] );

}

printf( "\n" );

for ( aucCoins[0] = 0; aucCoins[0] <= max[0]; aucCoins[0]++ )

{

for ( aucCoins[1] = 0; aucCoins[1] <= max[1]; aucCoins[1]++ )

{

for ( aucCoins[2] = 0; aucCoins[2] <= max[2]; aucCoins[2]++ )

{

for ( aucCoins[3] = 0; aucCoins[3] <= max[3]; aucCoins[3]++ )

{

for ( aucCoins[4] = 0; aucCoins[4] <= max[4]; aucCoins[4]++ )

{

if ( isGoodSet( aucCoins ) )

{

iTotal++;

printf( "\nGood set : %3d %3d %3d %3d %3d",

aucCoins[0], aucCoins[1], aucCoins[2], aucCoins[3], aucCoins[4] );

}

}

}

}

}

}

printf( "\nFound %d solutions.\n", iTotal );

}

// Function to determine if we have a good set of coins (adds up to the goal).

unsigned char isGoodSet( unsigned char aucCoins[] )

{

int i;

int iSum = 0;

for ( i = 0; i < NUM_COINS; i++ )

{

iSum += ( aucCoins[i] * ucCoinVal[i] );

}

return ( iSum == GOAL_IN_CENTS ) ? 1 : 0;

}