Select random item out of known number of items [duplicate] - javascript

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(39 answers)
How to get random element in jquery?
(7 answers)
Closed 8 years ago.
I have 8 divs to select from, they all have id's assigned to them, named not numerically, but descriptively. I want to be able to add .myClass to a div chosen at random out of these eight.
To generate a random number, I would use this JavaScript snippet:
var random = Math.round(Math.random()*10);
My questions:
How can I limit the random number to only 1 out of 8 possible values?
How can I add .myClass to a randomly chosen one div out of eight with a non-numeric id?

var randomNumber= 1 + Math.floor(Math.random() * 8);

How can I limit the random number to only 1 out of 8 possible values?
Store the 8 possible values in an array, A
Get a number between 0 and 7 (inclusive) using Math.random() and assign to X
The random number you want is A[X]
For ex:
var A = [2, 5, 6, 7, 8, 9, 11, 15];
var X = Math.floor(Math.random()*8);
var theNumber = A[X];

How about:
var random = Math.floor(Math.random()*8);
$("div:eq(" + random + ")").addClass("yourClassHere");
Edit: Was answering the question before it was edited, when selecting a random div was also needed.
Fiddle (thanks to smerney): http://jsfiddle.net/5JPWu/2/

var array= [2, 5, 6, 7, 8, 9, 11, 15];
var X = Math.floor(Math.random()*8);
Then use the following
varray[X];

Related

How to generate a random number from 2 numbers [duplicate]

This question already has answers here:
How to decide between two numbers randomly using javascript?
(4 answers)
Closed 1 year ago.
I've searched a lot for generating a random number but all I got is generating for a range between a or b.
I'm trying to get a number from a or b, i.e. either a or b, none from in between.
This returns the first value only
var number = 1 || 9; \\9
You can store your two numbers in an array and get a random index of that array. Here's an example:
var yourTwoNumbers = [2,5]
console.log(yourTwoNumbers[Math.floor(Math.random() * yourTwoNumbers.length)]);
So Math.random() randomly generates a number between 0.0 and 1.0. Math.random() < 0.5 has a 50% percent chance of either being true or false. This way you can select one of two numbers with equal probability.
let number = Math.random() < 0.5 ? 1 : 9;
console.log(number)
The same asked here: How to decide between two numbers randomly using javascript?
There is already an answer with explanations.
The Math.random[MDN] function chooses a random value in the interval [0, 1). You can take advantage of this to choose a value randomly.
const value1 = 1
const value2 = 9;
const chosenValue = Math.random() < 0.5 ? value1 : value2;
console.log(chosenValue)

the less than operator in javascript (<) is working as less or equals to [duplicate]

This question already has answers here:
Generate random number between two numbers in JavaScript
(32 answers)
Closed 1 year ago.
this code is supposed to display a random character/ letter of a given name in javascript using while loops and if statements . . .
the problem that I faced is that the RandomLetterIndex is between 0 and 5 (<=5) when I want it to be between 0 and 4 (<5)
const MyName = "Ayman";
var RandomLetterIndex = Math.floor(Math.random() * 10);
while (RandomLetterIndex > MyName.length) {
RandomLetterIndex = Math.floor(Math.random() * 10);
if (RandomLetterIndex < MyName.length && RandomLetterIndex !== 5) {
break
}
}
console.log(RandomLetterIndex);
console.log(MyName.charAt(RandomLetterIndex));
If you want the random number to be less than the length of the word, instead of using while loops, you can do this
var RandomLetterIndex = Math.floor(Math.random()*MyName.length);
multiplying by length instead of 10 makes sure that the value always lies in the range [0, length-1] instead of [0, 10-1]
The problem is with the 0 based index and the length property. MyName.length will equate to 5 and thus the while loop will stop and the consoles print out.
while (RandomLetterIndex > MyName.length - 1) {
Try like this with the minus 1.
Your while loop ends when RandomLetterIndex is 5. Thats why you see a five in the console.
Also, you are breaking the loop, and therefore the while check is kind of useless.

Javascript - return array of values that totals next number up

I am trying to work out the best way to achieve the following:
A score might require a total of 25 'items' AS A MINIMUM
currently that person might have 15.8 'items'
I have a number of items required to reach that score (9.2)
So to get that score the minimum a person must have is 10 'items' in x weeks (to be 25.8 and over the 25 threshold).
Assuming they have 4 weeks to do it that gives 2.5 needed per week.
What I am struggling with is how to output an array of 'whole items' that will make 10.
e.g.
2
3
2
3
I want the items to be as evenly distributed as possible.
so
1
2
3
4
would be useless
I am just trying to work out the best way to do this.
I was thinking of:
finding nearest whole number ROUNDED UP (3 in this example)
Then outputting that number
Then on the next pass gathering the 'remainder' (-0.5) and then rounding the number.
But it doesn't quite work for all cases.
Can anyone help me get my head around it without writing hundreds of lines of code.
As a further example say 17 were needed in 5 weeks that would be
4
3
3
4
3
Thanks in advance.
You could do it some way like this:
function myFunction(total, weeks) {
var n = 0;
var temp = 0;
var arr = [];
while (n < total) {
temp = n;
n += total / weeks;
arr.push(Math.floor(n) - Math.floor(temp));
}
return arr;
}
myFunction(10, 4); //[2, 3, 2, 3]
myFunction(17, 5); //[3, 3, 4, 3, 4]
In this code, total / weeks will be the average number you'll want to add to n to get from 0 to total in exactly weeks iterations.
Now the difference between the original value of n (which is stored in temp) and the new value of n is pushed to the array. That will give you the rounded numbers you'll need to add up to the entered total.

Generate random number within range without repeating numbers in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generate 8 unique random numbers between 1 and 100
Generate unique number within range (0 - X), keeping a history to prevent duplicates
I need loop that will run 80 times and generate random number between 0-79 but it will not repeat number that has been generated already.
How can I do that?
for (var i = 0, ar = []; i < 80; i++) {
ar[i] = i;
}
// randomize the array
ar.sort(function () {
return Math.random() - 0.5;
});
// You have array ar with numbers 0 to 79 randomized. Verify
console.log(ar);
// take out elements like this
ar.pop()

Javascript number placing and how to , 4 = 1.04, 14 = 1.14, 100 = 2.00 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript number placing and how to , 4 = 0.04, 14 = 0.14, 100 = 1.00
I am trying to write a custom calculator but I am having trouble trying to work out a figure, I want to be able to add decimal points before the number which has been inputed.
For example if the user puts in 4 I want the value in the string to look like this 1.04 and so on 14 = 1.14, 100 = 2.00.
I tried using the inbuilt function
var num = 4; fig = num.toFixed(2);
But that doesn't work, the only way I can think to do it is with if(val.length >2){ do something; } which would be a long way to do this. Has any body got any ideas for this?
This is very similar to your previous question: Javascript number placing and how to , 4 = 0.04, 14 = 0.14, 100 = 1.00
Let's say your user enters a figure which you assign to variable num. The result is given by
var result = 1 + (num / 100)
You could also just add 1 to the result given by any of the answers to your previous question.

Categories