Created
May 7, 2020 13:21
-
-
Save macroxela/4cb446b5af82cc9f56b2b81814e6d1d9 to your computer and use it in GitHub Desktop.
Find how many ways you can make change with infinite amount of coins c = [c1, c2, ..., cm] for change N
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############################################################################ | |
#Find how many ways you can make change with coins c = [c1, c2, ..., cm] | |
#for change N. Similar to the Subset Sum problem | |
# | |
############################################################################ | |
#Dynamic Programming Solution | |
def cchange(Cents, coins): | |
#Initialize matrix to store values | |
matrix = [[0 for i in range(0, cents+1)] for j in range(0, len(coins)+1)] | |
for i in range(0, len(coins)+1): matrix[i][0] = 1 | |
for i in range(1,len(coins)+1): #Iterate through all coins 0 coins - all coins | |
for j in range(0, cents+1): #Iterate through all possible total change 0 - cents | |
x = matrix[i-1][j] #When solution doesn't include current coin | |
y = 0 | |
if j-coins[i-1] >= 0: | |
y = matrix[i][j-coins[i-1]] #When solution includes current coin | |
matrix[i][j] = x+y #Combine both solutions | |
return matrix | |
#Recursive Solution | |
def coinchange(N, S, m): | |
if N < 0: | |
return 0 | |
if N == 0: | |
return 1 | |
if m <= 0 and N >= 1: | |
return 0 | |
c1 = coinchange(N, S, m-1) | |
c2 = coinchange(N-S[m-1], S, m) | |
return c1 + c2 | |
def printMat(matrix): | |
for i in matrix: | |
print(i) | |
coins = [1, 2, 3] | |
cents = 5 | |
print("Test 1:") | |
c = coinchange(cents, coins, 3) | |
x = cchange(cents, coins) | |
print("Final matrix with coins ", coins, " and ", cents, " cents is ") | |
printMat(x) | |
print("c = ", c, " and x = ", x[len(coins)][cents]) | |
print("") | |
coins = [1, 3, 5, 6] | |
cents = 10 | |
print("Test 2:") | |
c = coinchange(cents, coins, 4) | |
x = cchange(cents, coins) | |
print("Final matrix with coins ", coins, " and ", cents, " cents is ") | |
printMat(x) | |
print("c = ", c, " and x = ", x[len(coins)][cents]) | |
print("") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment