Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save jwgeller/9044e6da219942adcdeb98332cff9937 to your computer and use it in GitHub Desktop.

Select an option

Save jwgeller/9044e6da219942adcdeb98332cff9937 to your computer and use it in GitHub Desktop.
_The False Billiard Ball Problem
<p>TODO: this is a work in progress</p>
<p>Problem: Twelve billiard balls are provided. All but one weigh the same. You are provided a balance scale which can be used only three times. You must determine which ball has the odd weight and determine whether that ball is heavier or lighter than the others.</p>
<button id="sim_btn" onclick="generateAndTest()">Generate and Test</button>
<div id="solution_container"></div>
// ball_id: ball_weight
let ballIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let ballWeights = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 0,
8: 0,
9: 0,
10: 0,
11: 0,
12: 1,
};
function generateAndTest() {
ballIds = shuffle(ballIds);
let container = document.getElementById('solution_container');
container.innerHTML = '';
// first measurement
console.log(ballIds);
for (let i = 1; i <= ballIds.length / 2; ++i) {
let groupOne = ballIds.slice(0, i);
let groupTwo = ballIds.slice(i, i + i);
let remainder = ballIds.slice(i + i);
let sumOne = calculateSum(groupOne);
let sumTwo = calculateSum(groupTwo);
let html = '<p>Group One (' + i + ') ';
if (sumOne == sumTwo) {
html += '=';
} else if (sumOne < sumTwo) {
html += '<';
} else {
html += '>';
}
html += ' Group Two (' + i + ')</p>';
container.innerHTML += html;
}
}
// source: https://stackoverflow.com/a/2450976
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function calculateSum(balls) {
let sum = 0;
for (let i = 0; i < balls.length; ++i) {
sum += ballWeights[balls[i]];
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment