Determine if a number can be made with prepicked numbers and times

Assuming picksToUse and timesToUse are exactly the same as you declared them, here’s a way to know if you have enough of everything in stock to “pay up”. It’s a boolean function, which uses recursion. You would call it with the amount needed as parameter, and it would tell you right there if you have enough of everything.

Private Function HasCashInStock(amount As Integer, Optional index As Integer = 0) As Boolean
    Dim billsNeeded As Integer = amount \ picksToUse(index)

    If billsNeeded > timesToUse(index) Then
        Return False
    End If

    amount -= picksToUse(index) * billsNeeded

    If amount = 0 Then
        Return True
    End If

    Return HasCashInStock(amount, index + 1)
End Function

The \ is an integer division operator (in VB.NET, at least – I’m shamelessly letting you translate this code). If you’re not familiar with the integer division operator, well, when you use it with integer it gets rid of the floating numbers.

3 / 2 is not valid on integers, because it would yield 1.5.

3 \ 2 is valid on integers, and will yield 1.

That’s all there is to it, really. Oh yeah, and recursion. I like recursion, but others will tell you to avoid it as much as you can. What can I say, I think that a nice recursive function has elegance.

You can also totally copy this function another time, modify it and use it to subtracts from your timesToUse() array once you know for sure that there’s enough of everything to pay up.

If HasCashInStock(HereIsTheAmountAsInteger) Then
End If

Having two functions is not the leanest code but it would be more readable. Have fun!

Browse More Popular Posts

Leave a Comment