Set variable random number of dots - javascript

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());

Related

Looking to add a random number to html element? [duplicate]

Need help with Javascript to generate number in HTML. I'm close but can't get it to quite work. Help would be appreciated.
http://jsfiddle.net/xmPgR/251/
function getNumber() {
var minNumber = 0; // The minimum number you want
var maxNumber = 100; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
$('#myNumber').html(randomnumber); // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = getNumber; // Runs the function on click
document.getElementById("yourNumber").innerHTML = randomnumber;
<div id="myNumber"></div>
<p id="yourNumber">
</p>
Your onload works after the next statement, because it works asynchronously. And besides this, you use a randomnumber outside from it's scope, where it is not accessible.
So I suggest you to return the randomnumber from the function and use that function in the onload event handler. Inside that handler call your function, get the number and assign to your element's text.
And also if your getNumer's logic is to return the number, don't assign anything inside it, just return the number. It's responsibility is to return a random number. Pass the range to it, don't hard code: in another place you can need a random number in the different range. Other logic implement outside of that function.
function getRandomNumber(minRange, maxRange) {
return Math.floor(Math.random() * (maxRange + 1) + minRange);
}
window.onload = function() {
const rand = getRandomNumber(0, 100);
document.getElementById("yourNumber").innerHTML = rand;
$('#myNumber').html(rand);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myNumber"></div>
<p id="yourNumber"></p>
Here you go:
function getNumber() {
var minNumber = 0; // The minimum number you want
var maxNumber = 100; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
document.getElementById("myNumber").innerHTML = randomnumber; // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = getNumber; // Runs the function on click
<div id="myNumber"></div>
<p id="yourNumber">
</p>

write a javascript multiplication function that will return two separate results

As you can see from the embed below... my script is only returning one result(500). How can I rewrite my code so that I get both results? Thank you in advance for your advice.
function multiplier() {
var number = 25;
var multiplier20 = 20;
if (number && multiplier20); {
return number * multiplier20;
}
var multiplier1 = 1;
if (number && multiplier1); {
return number * multiplier1;
}
}
multiplier();
EDIT: hey guys thanks for the help. but I figured out what the problem was... I am not supposed to be returning an object only an number. So how do I edit this code to make it return only two numbers???
A function can only return one thing. A generator function (function*) however can yield as many numbers as you want:
function* multiplier() {
yield 25 * 20;
yield 25 * 1;
}
console.log(...multiplier())
You could also turn the results into an array easily:
const array = [...multiplier()];
(No this is not the easiest way, but im trying to propagate some cool js :))
You can try the following approach
function multiplier() {
var number = 25;
var multiplier20 = 20;
var res1 = 0;
var res2 = 0;
if (number && multiplier20); {
res1 = number * multiplier20;
}
var multiplier1 = 1;
if (number && multiplier1); {
res2 = number * multiplier1;
}
return {res1,res2};
}
var ret = multiplier();
console.log(ret);
Or alternatively....
function multiplier() {
return { result1: 25 * 20, result2: 25 * 1 }
}
You can return a string instead of 2 separate number and then, split it into two number. Something like this:
function multiplier(number) {
return number * 20 + '|' + number * 1;
}
var output = multiplier(20)
console.log(output.split('|')[0], output.split('|')[1]);

javascript random number looking for hasClass that doesn't exsist

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')

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

javascript - generate a new random number

I have a variable that has a number between 1-3.
I need to randomly generate a new number between 1-3 but it must not be the same as the last one.
It happens in a loop hundreds of times.
What is the most efficient way of doing this?
May the powers of modular arithmetic help you!!
This function does what you want using the modulo operator:
/**
* generate(1) will produce 2 or 3 with probablity .5
* generate(2) will produce 1 or 3 with probablity .5
* ... you get the idea.
*/
function generate(nb) {
rnd = Math.round(Math.random())
return 1 + (nb + rnd) % 3
}
if you want to avoid a function call, you can inline the code.
Here is a jsFiddle that solves your problem : http://jsfiddle.net/AsMWG/
I've created an array containing 1,2,3 and first I select any number and swap it with the last element. Then I only pick elements from position 0 and 1, and swap them with last element.
var x = 1; // or 2 or 3
// this generates a new x out of [1,2,3] which is != x
x = (Math.floor(2*Math.random())+x) % 3 + 1;
You can randomly generate numbers with the random number generator built in to javascript. You need to use Math.random().
If you're push()-ing into an array, you can always check if the previously inserted one is the same number, thus you regenerate the number. Here is an example:
var randomArr = [];
var count = 100;
var max = 3;
var min = 1;
while (randomArr.length < count) {
var r = Math.floor(Math.random() * (max - min) + min);
if (randomArr.length == 0) {
// start condition
randomArr.push(r);
} else if (randomArr[randomArr.length-1] !== r) {
// if the previous value is not the same
// then push that value into the array
randomArr.push(r);
}
}
As Widor commented generating such a number is equivalent to generating a number with probability 0.5. So you can try something like this (not tested):
var x; /* your starting number: 1,2 or 3 */
var y = Math.round(Math.random()); /* generates 0 or 1 */
var i = 0;
var res = i+1;
while (i < y) {
res = i+1;
i++;
if (i+1 == x) i++;
}
The code is tested and it does for what you are after.
var RandomNumber = {
lastSelected: 0,
generate: function() {
var random = Math.floor(Math.random()*3)+1;
if(random == this.lastSelected) {
generateNumber();
}
else {
this.lastSelected = random;
return random;
}
}
}
RandomNumber.generate();

Categories

Resources