javascript random number looking for hasClass that doesn't exsist - javascript

To make this fairly simple my comments in the code say what I'm trying to accomplish. My code when executed seems to not continue to calculate until it finds an .wrap with an empty class, which is what I'm trying to do. Maybe someone can help me figure out how to extend the infinite checking to eventually find an open .wrap which the class has not been defined.
function computerMove(){
//returns number between 1-9
var rand = Math.floor((Math.random() * 9) + 1);
console.log(rand);
//checks for if .wrap has class of x and if it does it should get another number
var check = $(".board .wrap:nth-child("+rand+")").hasClass("x");
if(check){
console.log("checking")
var rand = Math.floor((Math.random() * 9) + 1);
//I believe this should work and repeat the function
computerMove();
}
else{
$(".board .wrap:nth-child("+rand+")").addClass("o");
}

No, don't use recursive function when you don't have to. Use loop.
function computerMove(){
var check;
var rand;
do {
//returns number between 1-9
rand = Math.floor((Math.random() * 9) + 1);
console.log(rand);
check = $(".board .wrap:nth-child("+rand+")").hasClass("x");
} while (check)
$(".board .wrap:nth-child("+rand+")").addClass("o");
}
Or it could be simpler to "smartly" use jQuery selector
// Find all elements that do not have x class
var items = $(".board .wrap:not(.x)")
// Get a random element
var target = items[Math.floor(Math.random()*items.length)];
// Add o class to the target
$(target).addClass('o')

Related

How to find if an array has a random number [Math.floor((Math.random() * 10) + 1)] or not in it in js

I am trying to create a hangman game in html,css,js.
So i am now to give it a randomisation on based how the question will be displayed -
Create the Random number - Math.floor((Math.random() * 10) + 1)
First of all check if the array(this array contains which questions are already done) has the random number
if not
if yes
then allow the below statement to happen
then let the function run again and agiin until random number is not there in th array
First question based on the random number and second olso and so on
But actually i cannot figure out how to check in the array has the random number. I tried:-
this works
function NextQuestion() {
let done = ['1','2'];
let random = Math.floor((Math.random() * 10) + 1);
let include = done.includes('1');
if (include == true) {
alert('true');// this works
}
}
this doesn't
function NextQuestion() {
let done = ['1','2'];
let random = Math.floor((Math.random() * 10) + 1);
let include = done.includes(random);
if (include == true) {
alert('true');// this does not works
}
}
The difference is that in the first one it has includes('1'); but in second it has includes(random);
Do you know why this happens if you do please let me know and please give the solution to this problem
Thanks in advance.
This will explain why
let random = Math.floor((Math.random() * 10) + 1);
console.log(random)
console.log(
["1","2","3","4","5","6","7","8","9","10"].includes(random)
);
console.log(
[1,2,3,4,5,6,7,8,9,10].includes(random)
);
So your hangman will work if you store the random as they are created
#mplungian correctly answered the question you raised in your title. But I believe you are going the wrong way about it if want to ask a given number of questions in a random sequence. For this you should simply step through the questions array with a for loop. But before you do that the array should be shuffled:
function shfl(a){
// Durstenfeld shuffle:
for(let i=a.length;i>1;){
j=Math.floor(Math.random()*i--);
if (i!=j) [a[i],a[j]]=[a[j],a[i]]
}
return a
}
const q=[1,2,3,4,5,6,7,8,9,10];
shfl(q);
q.forEach((n,i)=>console.log(i+1+". Q"+n));

Random lottery number generator

What I'm trying to do is generate 6 random numbers, five in a range of 1-45 and one in a range of 1-25 for a Greek lottery game (Tzoker). The first 5 numbers should be unique. By pressing a button, I want to add these numbers to a div using jQuery (I have some working code for this part).
I thought it would be pretty easy using a loop, but I've found myself unable to check if the number generated already exists. The loop would only contain the first 5 numbers, because the last number can be equal to one of the other 5.
Let me propose you some simpler solution.
Make a list of all numbers from 1 to 45.
Sort the list using Math.random (plus minus something, read the docs of Array.sort to find out) as the comparison function. You will get the list in random order.
Take 5 first items from the list.
Then, when you already have the numbers, put them all into your div.
This way you don't mix your logic (getting the numbers) with your presentation (putting stuff into the DOM).
I leave the implementation as an exercise for the reader. :)
Like this?
$(function() {
$('button').on('click', function(e) {
e.preventDefault();
var numArray = [];
while( numArray.length < 5 ) {
var number = Math.floor((Math.random() * 45 ) + 1);
if( $.inArray( number, numArray ) == -1 ) {
numArray.push( number );
}
}
numArray.push( Math.floor((Math.random() * 25 ) + 1) );
$('div').html( numArray.join("<br />") );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Generate</button>
<div></div>
While this might be not exactly what you were asking for, if you would use lodash, this would be as simple as:
_.sample(_.range(1, 46), 5) // the 5 numbers from 1..45
_.random(1, 26) // one more from 1..25
This is why functional programming is so cool. You can read for example Javascript Allonge to find out more.
http://jsfiddle.net/015d05uu/
var tzoker = $("#tzoker");
var results = $("#results");
tzoker.click(function() {
results.empty();
var properResults = [];
var rand = 0;
var contains = false;
for (i = 1; i < 7; i++) {
do
{
(rand = Math.floor((Math.random() * (i != 6 ? 45 : 25)) + 1));
contains = properResults.indexOf(rand) > -1;
} while(contains)
results.append("<br />", rand, "<br />");
properResults.push(rand);
}
});
Here is the main idea of a solution. You can define the max value as a parameter for the random.
Then, check the existence of the item in a simple array with only the data you want.
You may use a general function which generates random numbers from 1 to maxValue, and adds them to an array only if they don't exist. Then, to display, cycle through the array items and append them to #randomNumbers.
HTML
<div id="randomNumbers"></div>
JS (with jQuery)
var randomNumbersArray = [];
$(function() {
generateRandomNumbers();
displayRandomNumbers();
});
function generateRandomNumbers() {
for (i = 0; i < 5; i++) {
generateRandomNumberFrom1To(45);
}
generateRandomNumberFrom1To(25);
}
function generateRandomNumberFrom1To(maxValue) {
var randomNumber;
do {
randomNumber = Math.ceil(Math.random() * maxValue);
} while ($.inArray(randomNumber, randomNumbersArray) > -1);
randomNumbersArray.push(randomNumber);
}
function displayRandomNumbers() {
for (i in randomNumbersArray) {
$("#randomNumbers").append(randomNumbersArray[i] + "<br>");
}
}

Using math.random in button to set a select option?

I'm trying to make a button that randomly sets a select option when clicked. I can't figure out what I am doing wrong though...
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/25/
$('#rand').click(
function() {
randNum();
var num = "";
document.getElementById("mySelect").value.innerHTML = favWebComics[num];
});
var randNum = function() {
num = Math.round(Math.random() * 2) + 1;
return num;
};
The shown code is only a small part of the larger script housed in the linked jsfiddle.
I plan to add more selections later, but I want to get the code figured out before I spend time on those.
Worth mentioning, my understanding of this is very limited, so keeping the advice simple is GREATLY appreciated.
The relevant part of your code that you will need to change will look like this when complete (see the updated jsfiddle):
$('#rand').click(function() {
var $select = document.getElementById('mySelect'),
max = $select.getElementsByTagName('option').length - 1;
$select.selectedIndex = randNum(1, max);
myFunction();
});
var randNum = function(min, max) {
num = Math.floor(Math.random() * (max - min + 1)) + min;
return num;
};
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("image").innerHTML = favWebComics[x][1];
document.getElementById("web").innerHTML = favWebComics[x][0];
document.getElementById("tags").innerHTML = "Tags: " + favWebComics[x][2];
};
I haven't changed the style or structure of your code, but just some of the basic properties.
The problem you have is with innerHTML. You cannot set innerHTML on an element's value.
Instead, what you can do is generate a random number and set the selectedIndex property of the select element to that random number.
Then, you'll call the function that displays the images and whatnot that you need.
You cannot change the select with innerHTML like this:
document.getElementById("mySelect").value.innerHTML = favWebComics[num];
You have to instead change the value, and apply the change like so
$("#mySelect").val("New text").change();
or
$("#mySelect").prop('selectedIndex', index).change();

Set variable random number of dots

I am trying to set a variable random number of dots. I can generate random numbers using Math.random(). I tried this without any luck:
function generate() {
Math.floor(Math.random() * 500)
}
var randomdots = generate();
What is the correct approach to set a variable random number of dots?
This method does nothing useful, it throws away the result before using it. Maybe you want:
function generate() {
var count = Math.floor(Math.random() * 500);
var result = '';
for (i = 0; i < count; ++i) {
result = result + '.';
}
return result;
}
document.write(generate());
Remember that functions in JavaScript must have a return if you want to get a value from them.
You can also use this
function generate() {
var index = Math.floor(Math.random() * 500);
return new Array(index).join(".");
}
var randomdots = generate();
You could have a JavaScript that writes bullets on page load. Do it like this:
var number = Math.ceil((Math.random() * 500)) + 1;
for (i=0;i<number;i++){
document.getElementById('output').innerHTML += '• ';
}
<p id="output"></p>
Let me know if you need additional help!
Although caslaner's answer seems to be the easiest way to achieve this, for educational purposes, here's a recursive function that does the same.
function generate(str,rm) {
if(rm === undefined) rm = Math.floor(Math.random() * 500);
return rm ? generate((str||'') + '.',rm-1) : str;
}
document.write(generate());

Random Number with javascript or jquery

I am trying to make a script to pick random number between two numbers . but it picks same number sometimes. i donot want to repeat same number until array is finished .
Here is my code
$(document).ready(function () {
abc();
test = array();
function abc() {
res = randomXToY(1, 10, 0);
$('#img' + res).fadeTo(1200, 1);
//$(this).addClass('activeImg');
//});
setTimeout(function () {
removeClassImg(res)
}, 3000);
}
function removeClassImg(res) {
$('#img' + res).fadeTo(1200, 0.1);
//$('#img' + res).removeClass('activeImg');
abc();
}
function randomXToY(minVal, maxVal, floatVal) {
var randVal = minVal + (Math.random() * (maxVal - minVal));
return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);
}
});
Does Anybody have idea about this ...
You'll have to maintain a list of numbers that have already been generated, and check against this list. Re-generate a new number if you find a dupe.
If you do not want the random numbers repeating themselves you have to keep track of the some way.
If you have the range you are dealing with is relatively small, you can create an array with all possible results and simply randomly pick out of it.
function Randomizer(minVal, maxVal, floatVal){
var possible_results = []; // for larger arrays you can build this using a loop of course
var randomization_array = [];
var count = minVal;
var incrementor = floatVal || 1; // set the distance between possible values (if floatVal equals 0 we round to 1)
while (count <= maxVal) {
possible_results.push(count);
count += incrementor;
}
this.run = function(){
// if randomization_array is empty set posssible results into it
randomization_array = randomization_array.length ? randomization_array : $.merge(randomization_array, possible_results);
// pick a random element within the array
var rand = Math.floor(Math.random()*randomization_array.length);
// return the relevant element
return randomization_array.splice(rand,1)[0];
}
}
and in order to use it (it creates a specialized object for each possible range):
rand = new Randomizer(1,10,0);
rand.run();
note that this approach does not work well for very large ranges

Categories

Resources