Here’s the jsfiddle update to handle subtraction:
https://jsfiddle.net/wvary/2u5xtkv2/8/
Function taken from the new fiddle:
//---Insert random pizza slices
function insertPizzas() {
selected = [];
result = 0;
//---Generate aleatory pieces
var rand = 0;
while (selected.length < 2) {
//---Making sure first number is greater than 0 (0 is the index so it is actually has a value of 1)
while (selected.length === 0 && rand === 0) {
rand = Math.floor(Math.random() * total);
console.log('first: ' + rand);
}
//---Making sure second number is greater than first number
while (selected.length === 1 && rand >= result) {
rand = Math.floor(Math.random() * total);
console.log('second: ' + rand);
}
//---Because of the number values, we can simply use the index difference as the values
//---Of course, we have to update our code if the values are different
if (selected.length === 0) {
result = rand;
} else {
result -= rand;
}
selected.push(rand);
}
//---Clear the slices
slices.html("");
//---Add the new slices
selected.forEach(function(number) {
var img = $("<img/>");
img.attr("src", pizzas[number].image);
slices.append(img);
});
}
A few things to take notice:
- We must loop in the first iteration to make sure the first index is not 0 because first number minus second number must be greater than 0 since our choices are 1 through 8.
- We must loop in the second iteration to make sure the second number is less than the first number for the same reason as #1.
- Since our values are all difference of 1, we can simply use index as our difference.
- Also we must initialize the rand value to 0 for the first loop to work.
10
solved Addition to Subtraction logic [closed]