Random no With no repeat [duplicate] - javascript

This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 8 years ago.
My code there are no of divs here, I have to select 5 randomaly at a time
<div id="#jpId1"></div>
<div id="#jpId2"></div>
<div id="#jpId3"></div>
<div id="#jpId4"></div>
<div id="#jpId5"></div>
<div id="#jpId6"></div>
<div id="#jpId7"></div>
<div id="#jpId8"></div>
<div id="#jpId9"></div>
<div id="#jpId10"></div>
<div id="#jpId11"></div>
I want in array (r), values of id's with no repeat but the values are repeated.... Any help is appreciable ... I have to use these ids for specific purpose
var itemp = ["#jpId1", "#jpId2", "#jpId3", "#jpId4", "#jpId5", "#jpId6", "#jpId7","#jpId8", "#jpId9", "#jpId10", "#jpId11"]
for (var i = 0; i < 5; i++) {
var r = itemp[Math.floor(Math.random() * itemp.length)];
alert(r);
}

Try this (splice removes the selected element from the source array) :
var r = [];
for (var i = 0; i < 5; i++) {
r.push(itemp.splice(
Math.floor(Math.random() * itemp.length), 1
)[0]);
}
alert(r);

You can check below code:
var nums = ["#jpId1", "#jpId2", "#jpId3", "#jpId4", "#jpId5", "#jpId6", "#jpId7","#jpId8", "#jpId9", "#jpId10", "#jpId11"],
ranNums = [],
i = 5,
j = 0;
k = 10;
while (i--) {
j = Math.floor(Math.random() * (k+1));
ranNums.push(nums[j]);
nums.splice(j,1);
k--;
}
console.log(ranNums);
And you can find link here http://jsfiddle.net/8Xb5g/1/

When you get the first random value from the array use the splice method to remove the that particluar value from the array.
var random = Math.floor(Math.random() * item.length);
item[random];
Then remove that particular value from array.
item.splice(random,1);
Use this in a loop it will give you everytym new value.

Here is the code:
var itemp = ["#jpId1", "#jpId2", "#jpId3", "#jpId4", "#jpId5", "#jpId6", "#jpId7","#jpId8", "#jpId9", "#jpId10", "#jpId11"];
id_arr=Array();
for (var i = 0; i < 5; i++) {
var r = itemp[Math.floor(Math.random() * itemp.length)];
if($.inArray(r, id_arr)>-1)
{
alert ("duplicate "+r+", hence discarded");
i--;
continue;
}
else
id_arr.push(r);
alert(r);
}
console.log(id_arr)
Fiddle

Related

Randomize insertion in for-loop

I'd like to randomize my HTML-output with multiple elements within my for-loop:
var h = document.getElementById("test_block");
for(i = 0; i < 7; i++) {
h.insertAdjacentHTML("afterend", "<div class='one_hour onesy'><p>Foo</p></div>");
}
With a random output within the forloop of:
<div class='one_hour onesy'><p>Foo</p></div>
<div class='two_hour onesy'><p>Loo</p></div>
<div class='three_hour onesy'><p>Too</p></div>
So I'd like to get the adjacented HTML to be randomly one of these lines.
How can I do that?
Lets see if this helps:
var results = [
'<div class="one_hour onesy"><p>Foo</p></div>',
'<div class="two_hour onesy"><p>Foo</p></div>',
'whatever',
...
];
for(i = 0; i < 7; i++) {
h.insertAdjacentHTML("afterend", results[Math.floor((Math.random() * results.length))]);
}

setAttribute() in a multi dimensional array

What I'm trying to figure out is how to give another class to certain div's in a two-dimensional array that has a value of "3" . This is what I tried at first.
numRows are the amount rows in the array.
numSeatsPerRow are the number of array items in every "numRows".
r and t are the positions in the two-dimensional array.
for(var r = 0; r<numRows; r++){
for(var t = 0; t<numSeatsPerRow; t++){
if(myArray[r][t] === 3){
document.getElementsByTagName("div")[r][t].setAttribute("class", "busySpot");
}
}
}
I soon understood that this wouldn't work. I tried to make a formula which could calculate every position as an ordinary array but couldn't make it work. Is there any other way to solve my problem?
In the code below I create a two-dimensional array based on two different inputs
var myArray = new Array(numRows);
for(var i = 0; i <numRows; i++){
myArray[i] = new Array(numSeatsPerRow);
}
In the next piece of code I give all array items the value 1 and then draw a green box for every item.
for(var h = 0; h<numRows; h++){
document.body.appendChild(//efter varje rad sker ett <br> i utskriften
document.createElement("br"));
document.body.appendChild(
document.createElement("br"));
for(var g = 0; g<numSeatsPerRow; g++){
myArray[h][g] = 1
var vSpot = document.createElement("div");
vSpot.className = "vacantSpot";
document.body.appendChild(vSpot);
}
}
What I'm trying to do in the top code is give the random boxes that I talked about another class.
this is how i came up with the random coordinates:
for(var v = 0; v < 15; v++){
var test = true;
while(test){
var x = Math.floor((Math.random() * numSeatsPerRow) + 0 );
var y = Math.floor((Math.random() * numRows) + 0);
if(myArray[x][y] === 1) {
myArray[x][y] = 3;
test = false;
}
}
}
Thanks!

How to store 3 random numbers in a single dimensional array and then get alerted in Javascript

function next_question()
{
for (i = 0; i <= 2 ; i++)
{
a = Math.floor(Math.random() * (8 - 0)) + 0;
ques_number[i] = a;
}
alert (ques_number[0]);
}
I want to create an Array, that has 3 random numbers in it and then get an alert of which numbers were stored in an Array! It seems simple but I'm doing something basically wrong here that my above code isn't working! Please help thanks
You need
a global variable ques_number,
two local variables i and a,
a simplified random part
var ques_number = [];
function next_question() {
var i, a;
for (i = 0; i <= 2 ; i++) {
a = Math.floor(Math.random() * 8);
ques_number[i] = a;
}
alert(ques_number[0]);
}
next_question();
document.write('<pre>' + JSON.stringify(ques_number, 0, 4) + '</pre>');

Random Numbers using Arrays Javascript

I am trying to add 8 random numbers to my array and display them. Right now, it is only displaying one random number, and I can't figure out why.
Code:
var array = [ ];
window.onload = function () {
var rand = Math.floor(Math.random() * 101);
for (var i = 0; i < 9; i++) {
array.push(rand);
answer = 'Your array is this: ' + array[i];
}
document.getElementById('result').innerHTML = answer;
}
You are overwriting the value of answer in each iteration of your loop, and then writing the final value of answer to your document.
Further, you also need to generate the random number in the loop, or you'll end up with the same number every time.
Instead of assigning the new value to answer in the loop, append it to answer:
var array = [ ];
var answer = '';
for (var i = 0; i < 9; i++) {
var rand = Math.floor(Math.random() * 101);
array.push(rand);
answer = answer + 'Your array is this: ' + array[i] + '<br/>';
}
document.getElementById('result').innerHTML = answer;
<div id="result"></div>
JSFiddle

something wrong with the letters placemeent on buttons

I am a very beginner in JavaScript / jQuery and got some difficulties with my code.
I am writing "Guess the word game" and the problem itself is that I have a 6-letters-length shuffled word from array and I need to place only one letter for one of 6 buttons. I have 6 buttons named from Letter1 to Letter6. Please, look through my code and say where is a mistake in placing it, thanks in advance. The code :
String.prototype.shuffle = function () {
var a = this.split(""),
n = a.length;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
}
$("#start").on('click', function () {
var rand = Math.floor(Math.random() * words.length);
var shuffledWord = words[rand].shuffle();
/*alert (shuffledWord);*/
for (var i = 0; i < shuffledWord.length; i++) {
$('Letter1').text(shuffledWord[i]);
$('Letter2').text(shuffledWord[i]);
$('Letter3').text(shuffledWord[i]);
$('Letter4').text(shuffledWord[i]);
$('Letter5').text(shuffledWord[i]);
$('Letter6').text(shuffledWord[i]);
}
});
The code itself works well, the problem is that I am doing something wrong with Letters.
You probably just need to make it $('#Letter1') etc.--i.e., I think you left off the # in referring to the letter elements.

Categories

Resources