JSFiddle - React, Tailwind, and code Playground
by Wentz Wu
HTML
<h1>A Quiz and Solution</h1>
<div id="source">
contributed from <a href=" http://www.xdxd.com.tw" target="_blank">XDXD</a>
and solved by <a href="http://nlabs.wordpress.com/" target="_blank">Bruce</a>
</div>
<p>A soft drink sells for 2 dollars per bottle. Consumers can redeem or exchange one bottle for free with 2 bottle caps or 4 bottle bodies. If you have 20 dollars, how many bottles of drinks you can receive?</p>
<label for="totalDollars">Your dollars</label>
<input id="totalDollars" type="text" name="totalDollars" value="20" />
<input id="submit" type="submit" value="Calculate" />
<div id="console1"></div>
CSS
h1 {
margin:0;
}
JavaScript
$("#submit").click(function (e) {
e.preventDefault();
console.clear();
var dollars = $("#totalDollars").val();
calculate(dollars);
});
function calculate(dollars) {
var bottles = Math.floor(dollars / 2);
var bc = new BottleCalculator(bottles);
bc.redeem();
console.prepend("<h1>" + bc.totalBottles + "</h1>");
}
function BottleCalculator(bottles) {
this.capsForRemption = 2;
this.bodiesForRemption = 4;
this.bottles = bottles;
this.bottlesRedeemed = 0;
this.totalBottles = bottles;
this.capsRemained = 0;
this.bodiesRemained = 0;
this.redeem = function (bottlesToRedeem) {
var bottles = (!bottlesToRedeem) ? this.bottles : bottlesToRedeem;
var bottlesFromCaps = Math.floor(bottles / this.capsForRemption);
var bottlesFromBodies = Math.floor(bottles / this.bodiesForRemption);
this.capsRemained += (bottles % this.capsForRemption);
this.bodiesRemained += (bottles % this.bodiesForRemption);
if (this.capsRemained >= this.capsForRemption) {
bottlesFromCaps += Math.floor(this.capsRemained / this.capsForRemption);
this.capsRemained = (this.capsRemained % this.capsForRemption);
}
if (this.bodiesRemained >= this.bodiesForRemption) {
bottlesFromBodies += Math.floor(this.bodiesRemained / this.bodiesForRemption);
this.bodiesRemained = (this.bodiesRemained % this.bodiesForRemption);
}
this.bottlesRedeemed = bottlesFromCaps + bottlesFromBodies;
var totalBottles = this.totalBottles;
this.totalBottles += this.bottlesRedeemed;
if (!bottlesToRedeem) console.log(totalBottles + " + " + this.bottlesRedeemed + " = " + this.totalBottles);
else console.log(totalBottles + " + " + this.bottlesRedeemed + " = " + this.totalBottles);
console.log("--");
console.log(this.capsRemained);
console.log(this.bodiesRemained);
console.log("==");
...