DEV Community

loading...

Discussion on: Daily Challenge #221 - The Merchant of York

Collapse
vidit1999 profile image
Vidit Sarkar • Edited

Hope I have got the problem right.
Here is a possible Python solution,

# amount : amount of pennies
# pigs : dict according to the structure of specs
#       Example:
#       pigs = {
#           'boar': { 'price': 10, 'qty': 1 },
#           'sow': { 'price': 5, 'qty': 1 },
#           'piglet': { 'price': 1, 'qty': 2}
#       }
def buyPigs(amount: int, pigs: dict) -> dict:
    oneBoarPrice = pigs['boar']['price'] / pigs['boar']['qty']
    oneSowPrice = pigs['sow']['price'] / pigs['sow']['qty']
    onePigletPrice = pigs['piglet']['price'] / pigs['piglet']['qty']

    # i : number of boar he can buy
    # j : number of sow he can buy
    # k : number of piglet he can buy
    for i in range(1, int(min(amount-1, amount/oneBoarPrice))):
        for j in range(1, int(min(amount-1, amount/oneSowPrice))):
            for k in range(1, int(min(amount-1, amount/onePigletPrice))):
                # Given that, the amount of pigs equals the amount of pennies
                # so (i+j+k) == amount
                # And, calculated total price == amount
                if i+j+k == amount == (oneBoarPrice*i + oneSowPrice*j + onePigletPrice*k):
                    return {'boar': i, 'sow': j, 'piglet': k}

    # if no case found then return this
    return {'error': 'Purchase not possible'}

Output,

pigs = {
    'boar': { 'price': 10, 'qty': 1 },
    'sow': { 'price': 5, 'qty': 1 },
    'piglet': { 'price': 1, 'qty': 2}
}

pigs2 = {
  'boar': { 'price': 5, 'qty': 1 },
  'sow': { 'price': 1, 'qty': 1 },
  'piglet': { 'price': 1, 'qty': 8 }
}

print(buyPigs(100, pigs)) # output -> {'boar': 1, 'sow': 9, 'piglet': 90}
print(buyPigs(150, pigs)) # output -> {'boar': 6, 'sow': 4, 'piglet': 140}
print(buyPigs(300, pigs)) # output -> {'boar': 3, 'sow': 27, 'piglet': 270}

print(buyPigs(100, pigs2)) # output -> {'boar': 7, 'sow': 61, 'piglet': 32}
print(buyPigs(41, pigs2)) # output -> {'boar': 7, 'sow': 2, 'piglet': 32}

Is the output of print(buyPigs(150, pigs)) right?

Collapse
savagepixie profile image
SavagePixie

Yes, my bad. I made a mistake when I submitted the challenge.

Collapse
shashankmistry31 profile image
Shashank Mistry

yes , even I got the same output for print(buyPigs(150, pigs)) .