Find Defect Light Weight Coin
Find Defect Light Weight Coin from Array of Coins Weight
by Shashi Badhuk
HTML
<div id="coins"></div>
<div id="defect-coin"></div>
<div id="weight-usage"></div>
CSS
div {
padding: 10px;
border: 1px solid #eee;
color: #323232;
}
JavaScript
let coins = [3, 2, 3, 3, 3, 3, 3, 3, 3];
let weightUsageCount = 0;
var optimizeUsage = function (coins) {
let n = coins.length;
if (n < 1) {
//If length is lower than 1, no coins are provided
return -1;
} else if (n == 1) {
//If one coin left, it is the lighter coin
printCoinInfo(coins[0]);
} else {
let set1 = coins.slice(0, parseInt(n / 2));
let set2 = coins.slice(parseInt(n / 2), 2*(n/2));
let set3 = coins.slice(2*parseInt(n/2), n);
var coin = diffScale(set1, set2);
if (coin == 0) {
//Set 1 is lighter
optimizeUsage(set1);
} else if (coin == 1) {
//Set 2 is lighter
optimizeUsage(set2);
} else {
//Balanced
optimizeUsage(set3);
}
}
};
var diffScale = function (coinSet1, coinSet2) {
weightUsageCount++;
let sum1 = coinSet1.reduce((a, b) => a + b, 0);
let sum2 = coinSet2.reduce((a, b) => a + b, 0);
if (sum1 < sum2) return 0;
else if (sum2 < sum1) return 1;
return -1;
};
var printCoinInfo = function(coin) {
document.getElementById("coins").innerHTML = "Array : "+JSON.stringify(coins)+ " | Total Coins : "+coins.length;
document.getElementById("defect-coin").innerHTML = "Defect Coin Weight : "+coin;
document.getElementById("weight-usage").innerHTML = "Weight Scale Usage : "+ weightUsageCount+" Times";
}
optimizeUsage(coins);