Generating Two Numbers With a Specific Sum - javascript

I'm trying to generate two numbers with a specific sum. Here is my proposed method:
Edited: http://jsfiddle.net/KDmwn/274/
$(document).ready(function () {
function GenerateRandomNumber() {
var min = -13, max = 13;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
}
var x = GenerateRandomNumber();
function GenerateRandomNumber2() {
var min2 = -13, max2 = 13;
var random2 = Math.floor(Math.random() * (max2 - min2 + 1)) + min2;
if ((random2 + x) == 0){
return random2};
}
var xx = GenerateRandomNumber2();
There's something wrong with the if ((random2 + x) = 0) line, as the code runs perfectly fine when it's removed. How can I modify this line so that the sum of the two numbers is 0? It would be most helpful if someone could modify the Jsfiddle that I've included. Thanks!

This is invalid:
if ((random2 + x) = 0){
You cannot assign something to an expression.
You probably meant to use the comparison operator (==), like this:
if ((random2 + x) == 0){

Are you trying to make it only output a second number that, when added to the first, equals 0? Because it actually already does that - but only if it gets it on the first try (try hitting refresh at least 30 times.) You need to tell it to keep re-choosing (looping) the second random number while the sum isn't 0:
function GenerateRandomNumber2() {
var min2 = -13,
max2 = 13;
var random2;
while ((random2 + x) !== 0) {
random2 = Math.floor(Math.random() * (max2 - min2 + 1)) + min2;
}
return random2;
}
http://jsfiddle.net/vL77hjp0/
To take this one step further, if I'm reading this right (if not ignore this) it looks like you might want to eventually choose a random sum and have it determine the required second number to be added. To do this, we would replace the 0 in our "while" loop with 'sum'. And 'sum' would have to be defined as a random number with a "max=x+13" and "min=x-13" (otherwise the random number may be too high/low for random2 to ever reach, causing the browser to crash.) [Or just remove the limits from random2.]
http://jsfiddle.net/fkuo54hc/

First, your GenerateRandomNumbers2 function returns undefined value other than in your if statement. So you need to return a value. I updated your fiddle and refactor some of your code.

Related

How to generate a unique no between1 and 10 but not equal to the current no or current value?

I want to generate a random number between 1 and 10 but it should not be equal to the current no or current value?
I looked at this below answer but having difficulty in making it as module since current no has to be retrieved from different file. I pretty much want something like this, but not exactly (if yo get what I mean).
Simple - just use a function which takes the current number, and generate a random number from 1-10 and, if it's equal to the current number, recalculate and re-check:
function newRandomNumber(currentNumber) {
var random = Math.floor(Math.random() * 10) + 1;
while (random == currentNumber) {
random = Math.floor(Math.random() * 10) + 1;
}
return random;
}
I have the below solution:
let previousValue = Math.floor(Math.random() * 10) + 1
for(let i = 0; i < 20 ; ++i) {
previousValue = (previousValue + Math.floor(Math.random() * 9)) % 10 + 1
console.log(new Date(), previousValue)
}
As you can see you create a previousValue to initiate the process. To generate another value between 1 and 10 but different than the previous one the solution is to generate a value between 0 and 9 and add it to the previous value. Using modulo operator you end up with a result in the correct range and different from the previous one.

Conflict when trying to generate two separate numbers

I have the following script, which is meant to generate 2 different numbers
<script type="text/javascript">
function GenerateRandomNumber2to6No1() {
var min = 2, max = 7;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
}
var GenerateRandomNumber2to6No1 = GenerateRandomNumber2to6No1();
$('.GenerateRandomNumber2to6No1').html(GenerateRandomNumber2to6No1);
function GenerateRandomNumber2to6No2() {
var min = 2, max = 7;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return (random !== GenerateRandomNumber2to6No1) ? random: GenerateRandomNumber2to6No2();
}
var GenerateRandomNumber2to6No2 = GenerateRandomNumber2to6No2();
$('.GenerateRandomNumber2to6No2').html(GenerateRandomNumber2to6No2);
</script>
NUMBER 1: <span class = "GenerateRandomNumber2to6No1"></span>
NUMBER 2: <span class = "GenerateRandomNumber2to6No2"></span>
This usually works fine but occasionally the page will load and no numbers will appear. I'm guessing this is when GenerateRandomNumber2to6No2 happens to generate the same number as GenerateRandomNumber2to6No1. I thought that
return (random !== GenerateRandomNumber2to6No1) ? random: GenerateRandomNumber2to6No2(); accounted for this, but perhaps instead of generating another unique number when there's redundancy, it generates no number at all. Is this the case? If so, how can I fix this?
Thanks!
function getRand(){
var array=[2,3,4,5,6,7]
var newArray=[];
for(var i=0;i<2;i++){
var ran=~~(array.length*Math.random());
newArray[i]=array.splice(ran,1)[0]
}
return newArray
}
var ranArray=getRand();
var ran1=ranArray[0];
var ran2=ranArray[1];
console.log(ran1,ran2)
getRand() is a function to give you an array of distinct numbers.Since you only need two,it only loop two times,and give you an array,which you can make use of it.
Back to your code,from what I see,Gno2 should keep running until it got another number,I don't know why.It's the time you try to debug.
First I will try to change the max=2 to max=3,if the code may not work for some number,then you can quickly realize and found out the problem is in these two functions.
Then try to log,console.log(Gno1,Gno2),see what exactly the numbers are,also help you to know where is the problem.
I think this piece of code can help you
var rand1,rand2;
var min = 3;
var max = 6;
do {
rand1 = Math.floor(Math.random() * (max - min)) + min;
rand2 = Math.floor(Math.random() * (max - min)) + min;
}while(rand1 === rand2);
$('.GenerateRandomNumber2to6No1').html(rand1);
$('.GenerateRandomNumber2to6No2').html(rand2);

JavaScript for Random Numbers with Recursion

I'm trying to create a javascript function that accepts 2 parameters min and max and generates a random number between the two integers. That part is easy.
Where things get rough is that I need to create a conditional that says
function generateNum (min, max) {
var randNumber = Math.ceil(Math.random()*(max - min)+min);
if (randNumber === max) {
// store the result (probably in an array) and generate a new
// number with the same behavior as randNumber (e.g. it is also
// stores it's total in the array and recursively "re-generates
// a new number until max is not hit)
}
}
The idea is to recursive-ise this so that a running total of the number of max hits is stored, combined, and then returned.
For example: The script receives min / max parameters of 5/10 generateNum(5,10){}. If the value generated by randNumber were 5, 6, 7, 8, or 9 then there would be no recursion and the function would return that value. If the value generated by randNumber is 10, then the value 10 is stored in an array and the function now "re-tries" recursively (meaning that as many times as 10 is generated, then that value is stored as an additional object in the array and the function re-tries). When the process stops (which could be infinite but has a parabolically decreasing probability of repeating with each recursion). The final number (5, 6, 7, 8, 9) would be added to the total of generated max values and the result would be returned.
Quite an unusual mathematic scenario, let me know how I can clarify if that doesn't make sense.
That part is easy.
Not as easy as you think... The algorithm that you have is broken; it will almost never give you the minimum value. Use the Math.floor method instead, and add one to the range:
var randNumber = Math.floor(Math.random() * (max - min + 1)) + min;
To do this recursively is simple, just call the method from itself:
function generateNum (min, max) {
var randNumber = Math.floor(Math.random()*(max - min + 1)) + min;
if (randNumber == max) {
randNumber += generateNum(min, max);
}
return randNumber;
}
You can also solve this without recursion:
function generateNum (min, max) {
var randNumber = 0;
do {
var num = Math.floor(Math.random()*(max - min + 1)) + min;
randNumber += num;
} while (num == max);
return randNumber;
}
There is no need to use an array in either case, as you don't need the seprate values in the end, you only need the sum of the values.
I assume that you don't really need a recursive solution since you tagged this for-loop. This will return the number of times the max number was picked:
function generateNum (min, max) {
var diff = max - min;
if(diff <= 0)
return;
for(var i = 0; diff == Math.floor(Math.random()*(diff + 1)); i++);
return i;
}
Example outputs:
generateNum(1,2) // 3
generateNum(1,2) // 1
generateNum(1,2) // 0
generateNum(5,10) // 0
generateNum(5,10) // 1
Two things:
1) the probability to roll 10 stays (theoretically the same on each roll (re-try)), the low probability is of hitting n times 10 in a row
2) I don't see why recursion is needed, what about a while loop?
var randNumber;
var arr = [];
while ((randNumber = Math.ceil(Math.random()*(max - min)+min)) === max) {
arr.push(
}
I'd consider an idea that you don't need to use not only recursion and arrays but not even a for loop.
I think you need a simple expression like this one (separated into three for clarity):
function generateNum (min, max)
{
var randTail = Math.floor(Math.random()*(max - min)+min);
var randRepeatMax = Math.floor(Math.log(Math.random()) / Math.log(1/(max-min+1)));
return randRepeatMax*max + randTail;
}
Assuming one random number is as good as another, this should give you the same distribution of values as the straightforward loop.
Recursive method:
function generateNum (min, max) {
var res = Math.floor(Math.random() * (max - min + 1)) + min;
return (res === max) ? [res].concat(generateNum(min, max)) : res;
}

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

JQuery create a random 16 digit number possible?

As the title says ... is it possible to create a random 16 digit number with jquery?
Just use:
Math.floor(Math.random()*1E16)
EDIT :
Note that there is about a 1/10 chance of a lower number of digits. If Math.random() generates something like 0.0942104924071337 then 0.0942104924071337 * 1E16 is 0942104924071337 which evaluates to 942104924071337; a 15 digit number.
The only way to 100% guarantee that the number is 16 digits in length is to have it be formed as a string. Using this method I would recommend #rjmunro's answer:
number = (Math.random()+' ').substring(2,10)+(Math.random()+' ').substring(2,10);
Not with jQuery, no, but you can do it with plain javascript.
If you want exactly 16 digits (possibly including leading 0s), I would start with Math.random(), convert to a string, pick 8 digits, and concatenate 2 runs together.
number = (Math.random() + '').substring(2,10)
+ (Math.random() + '').substring(2,10);
No, use JAVASCRIPT!
jQuery is not some magic genie.
This is a task which is much better suited for raw javascript. For example
var str = '';
var i;
for (i = 0; i < 16; i++) {
var number = Math.floor(Math.random() * 10) % 10;
str += number;
}
I just tried with #rjmunro 's answer.
Unfortunately, it does generate string less than 16digits,
but very rare, approxly once in 10 million times.
Here is my testing code, runs in nodejs:
'use strict';
var fs = require('fs');
var totalTimes = 100000000;
var times = totalTimes;
var fileName;
var writeStream;
while (times > 0) {
var key = (Math.random() + ' ').substring(2,10) + (Math.random() + ' ').substring(2,10);
times --;
if (key.length !== 16) {
var msg = 'a flaw key gened: ' + key + '\n';
// create a log file at first time
if (!fileName) {
fileName = 'log/flaw_key_' + new Date() + '.txt';
}
writeStream = fs.createWriteStream(fileName);
writeStream.write(msg);
writeStream.end();
}
if (times === 0) {
console.log(totalTimes + ' times key gened');
}
}
Also #Dimitri Mikadze 's answer generate less length string as well, so I eventually adopt a way with some concept of his solution:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Gen random digits string in specific length
* #param {Int} length of string
*
* #return {String}
*
*/
function genString(length) {
var times = length;
var key = '';
while (times > 0) {
times --;
key += getRandomInt(0, 9);
}
return key;
}
genString(16); // a 16 digits string
u can use this function to generate random digits, just pass minimum and maximum parameters
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
random 16 digit, usage
randomInt(0, 9999999999999999);
I know this question is old but this simple function will guarantee a 16 (or however many you want) character string every time without the 10% failure rate of other solutions. Can change it to a number if you need to.
function generate() {
let string = ""
while (string.length < 16) {
let number = Math.floor(Math.random() * 10).toString()
string += number
}
return string
}
I think this way is more beautiful:
const generateFixedLengthNumberInString = length =>
[...Array(length).keys()].reduce(
previousValue =>
previousValue + String(Math.floor(Math.random() * 10) % 10),
);
console.log(generateFixedLengthNumberInString(16))
// prints "0587139224228340"

Categories

Resources