checking rolled by image number? - javascript

So, I have a code that is rolling a random number from 1024 to 4096 and changing backgroundPosition to rolled number. (jsfiddle)
function slide()
{
var x = 1;
var y = 30;
var z = Math.floor((Math.random() * 4096) + 1024); // background offset
var zz = Math.floor((Math.random() * 14) + 0); // number
var clr = setInterval(function()
{
if(x >= z) x = 1;
document.getElementById("slide").style.backgroundPosition = x+"px 0px";
x+=y;
y-=0.1;
if (y<=0)
{
clearInterval(clr);
document.getElementById('rolledNumber').innerHTML = z;
}
}
,10);
}
"z" is a random number between 1024 and 4096, how can I check what number on image it is? I tried if (z >= 2285 && z <= 2210){var zz = 4;}, where "zz" is a number on image, but it's not working.
Hope you guys can understand it.

You have a few problems here:
1) if (z >= 2285 && z <= 2210)
is impossible. There is no number that satisfies both "larger than 2284" AND "smaller than 2211".
2) "z" is a random number between 1024 and 4096
var z = Math.floor((Math.random() * 4096) + 1024); will actually create a random number between 1024 and 5120. Imagine the case where Math.random() returns 1. Your result would be 1 * 4096 + 1024, or 5120.
3) Your background image is repeating - if you stick to one set of 15 numbers, you could access the number by mapping the pixel offset to an array.. something like this:
var boxWidth = 150;
var boxes = [1, 14, 2, 13, 3, 12, 4, 0, 11, 5, 10, 6, 9, 7, 8];
function getNumber (offset) {
var boxNumber = Math.floor(offset / boxWidth);
return boxes[boxNumber];
}
4) No one knows the application of this logic other than you, please reword your question such that it actually makes any sense and act like you've tried to find the problem yourself.

If anyone is interested - I figured out how to do this. I'm checking "x" value, and if it's between x and y, that means rolled number is z. Fragment of code:
if (x >= 410 && x <= 485){var rolledNumber = 1;}
if (x >= 335 && x <= 410){var rolledNumber = 14;}
if (x >= 260 && x <= 335){var rolledNumber = 2;}

Related

Javascript for loop conditional iterations and resetting variable

With the following code, I'm looping through an array of colors (favorites), creating rectangles for a jsPDF document.
After 5 iterations, I want to reset the x variable back to startX and then add 1.875 with each iteration. Likewise for the next 5 iterations: reset x to startX adding 1.875 until 10, then again until 15.
I'm just not having any luck resetting x in these conditionals. I'm sure it's something obvious but what am I missing here?
Or should I structure the loop in a different way?
What I'm trying to accomplish is create up to 3 rows of 5 rectangles. Once I hit 5, start a new row, hence the reset of x which is a page location coordinate.
let startX = 1
let startY = 1
let secondY = 4
let thirdY = 6.5
let n = favorites.length
for (let i = 0, x = startX, y = startY; i < n; x += 1.875, i++) {
if (i < 5) {
doc.setFillColor(favorites[i].h)
doc.rect(x, y, 1.5, 1, 'F')
doc.text(favorites[i].h.toString(), x, y + 1.5)
} else if (i >= 5 && i < 10) {
x = 1 // resets but then doesn't increment
y = secondY
doc.setFillColor(favorites[i].h)
doc.rect(x, y, 1.5, 1, 'F')
doc.text(favorites[i].h.toString(), x, y + 1.5)
} else if (i >= 10 && i < 15) {
x = 1 // resets but then doesn't increment
y = thirdY
doc.setFillColor(favorites[i].h)
doc.rect(x, y, 1.5, 1, 'F')
doc.text(favorites[i].h.toString(), x, y + 1.5)
}
}
You can use the modulo operator (%), and set x and y outside the loop declaration:
const yValues = [1, 4, 6.5];
for (let i = 0 ; i < 15; i++) {
const x = 1 + ((i%5) * 1.875);
const y = yValues[Math.floor(i/5)];
// commented lines to make this example run
// doc.setFillColor(favorites[i].h)
// doc.rect(x, y, 1.5, 1, 'F')
// doc.text(favorites[i].h.toString(), x, y + 1.5)
console.log({x,y});
}
Incrementation in a for loop occur before any commands in the loop. Right now, every iteration in your second and third if blocks resets x to 1, and always does so after x's incrementation in the for loop, thus overwriting it. That's why x isn't changing.
A better approach might be to increment only i, and set x to depend on i's value, something like this:
x = 1 + ((i - 5) * 1.875)
x = 1 + ((i - 10) * 1.875)
And actually, it would be even better to use startX instead of 1:
x = startX + ((i - 5) * 1.875)
x = startX + ((i - 10) * 1.875)

How can I calculate my odds of x happening?

What is the percent change of this code reaching the number 200, 500 and 1000?
I created this code for 200 to be 50% but it keeps rolling numbers above 200, someone please help me if you understand :D.
var mainMultplier = 100;
var numerator = 99;
var denominator = 100;
for(;;) {
var randomInt = random.real(0, 1.0);
if ( numerator/denominator > randomInt ) {
numerator = numerator + 1;
denominator = denominator + 1;
mainMultplier = mainMultplier + 1;
} else {
break;
}
}
Edit
Based on the code you have posted, we can see these two base rules:
P(100) = 1 - 0.99 = 0.01
P(101) = (1 - P(100)) * (1 - (100 / 101)) = P(101) = (1 - P(100)) * (1 / 101)
The second rule can be generalized for any number X after 100:
P(X) = (1 - P(X - 1)) * (1 / X)
Now, I did learn how to do proofs by induction at Uni, which I'm sure would help my explanation here, but I can't remember it anymore :(. So instead, I've written some code to generate a lookup table p, from 100 to 1000:
var p = [];
p[100] = 0.01;
for (var x = 101; x <= 1000; x++)
p[x] = (1 - p[x - 1]) * (1 / x);
Edit 2
And that's as far as my help can go. You may want to post the generalized algorithm on the Software Engineering page.

jQuery for each 24 over a number

I have this code
if ($('input#grommet').is(':checked')) {
if (width <= 96) {
var grommetQTY = 4;
} else if (width > 96) {
grommetQTY = (Math.floor(width / 24));
grommetQTY = grommetQTY - 4;
grommetQTY = grommetQTY * 2;
grommetQTY = grommetQTY +4;
}
}
and I need to add 2 to the grommetQTY for each whole 24 inches (2 feet) over 96 width. Is there a way to do this?
What this is attempting to accomplish is giving the pricing for a banner. We add 2 more grommets at 2 feet intervals, but because this is custom sizing, it could be 96 feet wide, and I don't want to have to write an else if statement for each two foot interval. I am hoping there is a way to only add two to the quantity everytime the width goes another 24 inches over the standard 96 inch width so if width is 96 or less, qty is 4, at 120 its 6, at 144 its 8, etc
Rather than coming up with the equation for this, here is a for loop that will do what you need:
var grommetQTY = 0;
for(var i = 96; i < n; i++)
if(i%24 == 0)
grommetQTY += 2;
where n is the length. This is terrible inefficient and could be sped up by just doing:
var grommetQTY = 0;
for(var i = 96; i < n; i+=24)
grommetQTY += 2;
This is nicer but still not ideal. The ideal solution in your case would be an equation.
P.S - The equation is Math.floor( Math.max((n - 96), 0) / 24 ) * 2 + 4 if I understand you correctly.
You could do something like this:
var extra = width - 96
var grommetQTY = 4;
if (extra > 0) {
grommet += Math.floor((extra / 24)) * 2;
}
The variable extra holds, as the name implies, extra length that you would want to take into consideration. If it's 0 or below that means it's 96 and under.
Then, for extra > 0 you could alternatively change it to extra >= 24 as any extra value less than 24 will return 0.
Math.pow(2, grommetQTY) * (Math.floor(96 / 24))
2 to the grommetQTY for each whole 24 inches in 96. Is that what you need?
Math.pow(a, b) gives a to the power of b
Edit:
var qty = (Math.floor(n / 24)) * 2
Where n is the pixels (96 in your example).
Edit:
var qty = 4 + ((width > 96) ? ((Math.floor((width - 96) / 24) * 2) : 0);
Is that it?

How do you make a variable have a 50 percent chance of being one value and 50 percent chance of being another?

a = document.getElementById("find").value
if (a == 'Spark' || a == 'Fire') {
var monster = x
var player = y
var damage = Math.floor(Math.random() * 25)
var damageplayer = Math.floor(Math.random() * 30)
alert('Your squad succeeded the enemy has ' + (x = x - damage) + ' original territories!');
alert ('You have' + (y = y - damageplayer) + 'original territories!'); }
This is my code above I'm trying to make it so that it is a 50/50 chance whether damage will = Math.Floor(math.random () *25) or = 0 . I tried multiplying a math .random by 1 then math. random by 25 and didn't work. How do you make it so 50 percent of the time it will equal 0 and the other 50 percent of the time equal math.random * 25?
Here's one way:
var coin = function() {
return (Math.random() < 0.5 ? 0 : 1);
}
var damage = 25*coin();
Sometimes I wonder how random Math.random really is...
An alternative:
return (new Date().getMilliseconds() % 2);
Don't use floor() as it will always round down. Use round()
var zeroOrOne = Math.round(Math.random());
var damage = zeroOrOne * Math.floor(Math.random() * 25);
Or, if you are one of those "cram as much code into one line as possible" folks:
var damage = Math.round(Math.random()) * Math.floor(Math.random() * 25);
damage = (Math.random() < 0.5) ? 0 : (Math.random() * 25);
Try with
var aux = Math.random()
if (aux < 0,5){
aux = 0
}else{
aux = damage
}
Then you can use the var aux for ur porpose instead of damage
I found a way:
Math.random();
if(Math.random() >= 0.5){ \\set variable to value A }
else { \\set variable to value B }
Since Math.random will randomly select a number 0 to 1 I set the check halfway, at 0.5.

Generate axis scale

I am working on a project where I need to calculate some scale for slider. The user can define min, max and step.
You can find the code below:
var j = Math.round(cfg.max / cfg.step);
var l = (containerWidth / (j - 1));
for (var i = 0; i < j; i++) {
s.push('<span style="left:');
s.push(l * i);
s.push('px">');
s.push(cfg.step * (i + 1));
s.push('</span>');
}
Example: min=1 max=12 step=3
Generated scale: 3 6 9 12
Slider ticks: 1 4 7 10 12
I would like to know how I can generate ticks for slider.
Assuming your question can be rephrased like this:
Calculate n ticks for an arbitrary range with min x and max y
Then we can adapt the linear tick function from D3.js:
function calculateTicks(min, max, tickCount) {
var span = max - min,
step = Math.pow(10, Math.floor(Math.log(span / tickCount) / Math.LN10)),
err = tickCount / span * step;
// Filter ticks to get closer to the desired count.
if (err <= .15) step *= 10;
else if (err <= .35) step *= 5;
else if (err <= .75) step *= 2;
// Round start and stop values to step interval.
var tstart = Math.ceil(min / step) * step,
tstop = Math.floor(max / step) * step + step * .5,
ticks = [];
// now generate ticks
for (i=tstart; i < tstop; i += step) {
ticks.push(i);
}
return ticks;
}
This isn't exactly to your specifications - it generates a set of nicely-rounded ticks, often 1-2 more or fewer than tickCount:
calculateTicks(1, 12, 5); // [2, 4, 6, 8, 10, 12]
calculateTicks(0, 12, 4); // [0, 5, 10]
It's hard to come to an optimum solution here, but I think the D3 approach does it relatively well - in my opinion, I'd rather have the ticks 2, 4, 6, 8, 10, 12 for a range 1-12 than the ticks 1, 4, 7, 10, 12 that you suggest.
Working fiddle: http://jsfiddle.net/nrabinowitz/B3EM4/

Categories