Skip to content

Instantly share code, notes, and snippets.

@precious
Last active September 23, 2017 13:14
Show Gist options
  • Save precious/bc2b567431c2ce2e9daf523f82039d38 to your computer and use it in GitHub Desktop.
Save precious/bc2b567431c2ce2e9daf523f82039d38 to your computer and use it in GitHub Desktop.
'use strict';
class Bidder {
constructor(quantity, cash) {
/*
quantity: integer even number of lots
each time exactly 2 lots are sold
so there will be exactly quantity/2 iterations
it's guaranteed that this number is positive
cash: integer number, amount of cents
it's guaranteed that this number is positive
*/
}
placeBid() {
/*
returns the next bid for the product, which may be zero
must be non-negative integer
*/
return 0;
}
bids(own, other) {
/*
shows the bids of the two bidders
will be called before each 'placeBid' call except the first one
*/
}
}
function run(first_bidder_class, second_bidder_class, quantity, cash) {
/*
returns 1 or 2 depending on which bidder won
returns 0 on draw
*/
if (quantity % 2 !== 0) {
throw `quantity should be even! got ${quantity} instead.`
}
let bidder1 = new first_bidder_class(quantity, cash),
bidder2 = new second_bidder_class(quantity, cash),
bid1,
bid2,
score1 = 0,
score2 = 0,
spent1 = 0,
spent2 = 0;
while (quantity > 0) {
if (typeof bid1 !== 'undefined' && typeof bid2 !== 'undefined') {
// call always except the 1st iteration
bidder1.bids(bid1, bid2);
bidder2.bids(bid2, bid1);
}
// make bids
bid1 = parseInt(bidder1.placeBid());
bid2 = parseInt(bidder2.placeBid());
// validate
if (Number.isNaN(bid1) || bid1 < 0) {
throw 'First bidder has returned incorrect bid';
}
if (Number.isNaN(bid2) || bid2 < 0) {
throw 'Second bidder has returned incorrect bid';
}
// validate total sum
spent1 += bid1;
spent2 += bid2;
if (spent1 > cash) {
throw 'First bidder has exceeded given cash amount';
}
if (spent2 > cash) {
throw 'Second bidder has exceeded given cash amount';
}
// give scores
if (bid1 > bid2) {
score1 += 2;
} else if (bid2 > bid1) {
score2 += 2;
} else {
score1 += 1;
score2 += 1;
}
quantity -= 2;
}
if (spent1 !== cash) {
throw `First bidder has not spent all cash, remaining sum: ${cash - spent1}`;
}
if (spent2 !== cash) {
throw `Second bidder has not spent all cash, remaining sum: ${cash - spent2}`;
}
return score1 > score2 ? 1 : score2 > score1 ? 2 : 0;
}
function runNTimes(N, first_bidder_class, second_bidder_class, quantity, cash) {
let totalScore1 = 0,
totalScore2 = 0,
result;
for (let i = 0; i < N; i++) {
result = run(first_bidder_class, second_bidder_class, quantity, cash);
if (result === 1) {
totalScore1 += 1;
} else if (result === 2) {
totalScore2 += 1;
}
}
console.log(`1st Bidder: ${totalScore1} (${N - totalScore2} with draws)`);
console.log(`2nd Bidder: ${totalScore2} (${N - totalScore1} with draws)`);
console.log(` Draws: ${N - totalScore1 - totalScore2}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment