Last active
November 10, 2020 21:59
-
-
Save anushshukla/f96371a940628115d1c4683d6dc57378 to your computer and use it in GitHub Desktop.
Find the maximum number of chocolates as per the price of a chocolate and exchange offer of wrappers for a chocolate
This file contains hidden or 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
| const getChocolates = (amount, price) => Math.floor(amount/price); | |
| const getChocolatesExchangedCount = (chocolates, wrapperExchangeRate, totalExchangedChocolates = 0) => { | |
| const exchangedChocolates = Math.floor(chocolates/wrapperExchangeRate); | |
| const remainingChocolates = chocolates%wrapperExchangeRate; | |
| const totalRemainingChocolates = exchangedChocolates + remainingChocolates | |
| totalExchangedChocolates += exchangedChocolates; | |
| if (totalRemainingChocolates < wrapperExchangeRate) { | |
| return totalExchangedChocolates; | |
| } | |
| return getChocolatesExchangedCount(totalRemainingChocolates, wrapperExchangeRate, totalExchangedChocolates); | |
| } | |
| const inputs = [{ | |
| budget: 15, | |
| rate: 1, | |
| wrapper: 3 | |
| }, { | |
| budget: 16, | |
| rate: 2, | |
| wrapper: 2 | |
| }, { | |
| budget: 20, | |
| rate: 3, | |
| wrapper: 5 | |
| }]; | |
| inputs.map(input => { | |
| const { budget, rate, wrapper } = input; | |
| console.log(`Budget: ${budget}`); | |
| console.log(`Rate: ${rate} per chocolate`); | |
| console.log(`Wrapper Exchange Offer: 1 chocolate for every ${wrapper} wrappers`); | |
| const chocolatesPurchased = getChocolates(budget, rate); | |
| console.log(`Chocolates Purchased: ${chocolatesPurchased}`); | |
| const chocolatesExchanged = getChocolatesExchangedCount(chocolatesPurchased, wrapper); | |
| console.log(`Wrappers Exchanged for Chocolates: ${chocolatesExchanged}`); | |
| console.log(`Total Chocolates: ${chocolatesPurchased + chocolatesExchanged}`); | |
| console.log("==========") | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment