While I was taking a break from programming, I saw a random post on 9gag and I thought I make a script for it.
A shop sells 1 chocolate at $1. You can exchange 3 wrappers for 1 chocolate. If you have $15, how many chocolates can you get?
var getChocolates = function(dollar) {
var price = 1, // Price per chocolate
wrappersForChocolate = 3; // Amount wrappers per exchange
var chocolates = Math.floor(dollar/price); // Round up no integers
if(chocolates < 0) return 0;
var count = 0;
do {
var exchanged = Math.floor(chocolates/wrappersForChocolate);
var leftover = chocolates%wrappersForChocolate;
var ate = exchanged * wrappersForChocolate;
count += (ate < wrappersForChocolate) ? chocolates : ate;
console.log('- chocolates:', chocolates, '- ate:', (ate < wrappersForChocolate) ? chocolates : ate);
chocolates = (chocolates < wrappersForChocolate) ? 0 : leftover + exchanged;
} while (chocolates);
return count;
}
Let’s run this
var dollar = 15;
var chocolates = getChocolates(dollar);
console.log(chocolates);
// 22
The answer is: 22
Dollar:
For ${{ dollar }}, you'll get {{ chocolates }} chocolates!!
Made simplified version
var getChocolatesSimplified = function(dollar) {
var price = 1, // Price per chocolate
wrappersForChocolate = 3, // Amount wrappers per exchange
exchangedToChocolate = 1; // Amount chocolates after exhange
var chocolates = Math.floor(dollar/price); // Round up no integers
if(chocolates < 0) return 0; // Returns 0;
var amountChocolate = Number(chocolates); // Copy amount
var count = 0;
do {
if(chocolates < wrappersForChocolate) break;
console.log('- chocolate:', chocolates);
chocolates = chocolates -wrappersForChocolate+exchangedToChocolate;
count++;
}
while (!(chocolates < wrappersForChocolate));
return amountChocolate + count;
}