javascript: generate 2 random but distinct numbers from range - javascript

quick question:
What is the best way for implementing this line of python code (generates two random but distinct numbers from a given range)...
random.sample(xrange(10), 2)
...in Javascript?
Thanks in advance!
Martin

Here is my attempt using splice:
var a = [1,2,3,4,5,6,7,8,9,10];var sample = [];
sample.push(a.splice(Math.random()*a.length,1));
sample.push(a.splice(Math.random()*a.length,1));
Wrapped in a function:
function sample_range(range, n) {
var sample = [];
for(var i=0; i<n; i++) {
sample.push(range.splice(Math.random()*range.length,1));
}
return sample;
}
var sample = sample_range([1,2,3,4,5,6,7,8,9,10], 2);
We could also stick the function into Array.prototype to have something like dot notation syntax:
Array.prototype.sample_range = function(n) {
var sample = [];
for(var i=0;i<n;i++) {
sample.push(this.splice(Math.random()*this.length,1));
}
return sample;
};
var sample = [1,2,3,4,5,6,7,8,9,10].sample_range(2);

If you want to generate random numbers between 0 and n, one way is to randomly pick number r1 in 0..n then pick r2 from 0..n-1 and add 1 to r2 if r2 >= r1.

function sample(range,tot){
if(tot > range){
alert('infinite loop?');
return [];
}
var myRandomNumbers = [];
for(var i = 0; i<tot; i++){
var randN = Math.floor(Math.random()*range);
while(myRandomNumbers.contains(randN)){
randN = Math.floor(Math.random()*range);
}
myRandomNumbers.push(randN);
}
return myRandomNumbers
}
var nums = sample(10,2); //array containing 2 distinct random numbers

Generate one, then repeatedly generate the second until it's not the same as the first. Tiny chance it will have to run longer, but you won't see any performance hit unless you need to generate billions of numbers.

Related

How do I divide numbers from two arrays into a new one. I am trying to make a rational zeroes thereom calculator of sorts for fun

This is as far as I've gotten. I have factored the numbers successfully, but I just need to distribute and divide them into the pOverQ array.
var p = readInt("What is your p: ");
var q = readInt("What is your q: ");
var factorP = [];
var factorQ = [];
var pOverQ = [];
var num = 0;
function start(){
factor(p, q);
println(factorP);
println(factorQ);
p_Q(p, q);
println(pOverQ);
}
function factor(p ,q){
for(var i = 1; i <= p; i++) {
if(p % i == 0){
factorP.push(i);
}
if(q % i == 0){
factorQ.push(i);
}
}
}
function p_Q(p, q){
for(var i = 0; i < (factorP.length)*2; i++){
pOverQ.push(factorP[i]/factorQ[i]);
}
}
I hope you can help!!!
It looks like you are trying to build something like this:
rational zeros theorem calculator
Here are a few steps towards it:
function factor(p){ // find all factors of a single number
let res=[];
for(let i=1;i<=p;i++) if(p%i == 0) res.push(i);
return res;
}
function p_q(P,Q){ // combine P- and Q-arrays and find all distinct fractions
const coll={}, qarr=factor(Q);
factor(P).forEach(p=>qarr.forEach(q=>{
let frac=reduce(p,q);
coll[frac.join("/")]=frac
}));
return coll;
}
// https://stackoverflow.com/a/4652513/2610061
function reduce(num,den){ // reduce a given fraction
// greatest common denominator:
function gcd(a,b){return b ? gcd(b, a%b) : a;};
const g = gcd(num,den);
return [num/g, den/g];
}
const res=p_q(6,7);
console.log(Object.keys(res)); // show the fractions as text ...
console.log(Object.values(res).map(([n,d])=>n/d)); // ... and as values
As #jsN00b already mentioned, you will need to consider both, positive and negative values of the calculated fractions as possible solutions for your polynomium. But I 'll leave that bit to you.

Number of combinations in a given number array in javascript

var ans = (49*48*47*46*45*44)/(6*5*4*3*2*1)
alert(ans.toLocaleString())
This will output 13,983,816 and it's the correct number of possible combinations from a number array of 1 to 49.
How do I implement this with numbers that I can get from 2 variables?
For example if I want to calculate the number of combinations possible for 5 numbers out of 40 I need to have (40*39*38*37*36)/(5*4*3*2*1) and I need this to be replaced like: 40*39*38*37*36 with var n and (5*4*3*2*1) with var t but output the correct order of numbers.
Just to be clear, I don't want to write these operations manually in the variables, I want the number specified in the variables to generate the operations based on their value. If I specify 6 selections I need to generate 6*5*4*3*2*1, if I specify 5 selections it needs to generate 5*4*3*2*1 and so on.
Thanks for the help!
Updated, (with loops):
Number.prototype.to = function(to){
var result = 1;
while(this >= to) result *= to++;
return result
};
var n = 49..to(44); //49*48*47*46*45*44
var t = 6..to(1); //6*5*4*3*2*1
document.writeln((n/t).toLocaleString())
You can try for loops:
function binom(a,b) {
if(a < 2*b) b = a-b;
var n = 1;
for(var i=a-b+1; i<=a; ++i) n *= i;
for(var i=2; i<=b; ++i) n /= i;
return n;
}
Nevermind, I managed to figure it out after some good hours:
function getChance(numbers, out_of) {
return numbers>0?out_of/numbers*getChance(numbers-1,out_of-1):1;
}
var np = 6; //numbers picked
var tn = 49; //total numbers
var ntm = 6; //numbers to match
var picks = getChance(np-ntm, tn-ntm);
var combs = getChance(np, tn);
var probs = combs/picks;
document.getElementById('chance').innerHTML = (probs | 0).toLocaleString();

Javascript get random variables from array but each just once

I´d like to get random variables from a javascript and prepend it to a div container like that:
// my Array
var thumbnailArray = new Array();
thumbnailArray[0] = 'contentarray1';
thumbnailArray[1] = 'contentarray2';
thumbnailArray[2] = 'contentarray3';
function thumbnailquery () {
for (var i = 0; i <= 3; i++) {
$('#myDiv').prepend(thumbnailArray[Math.floor(Math.random() * thumbnailArray.length)])
}
}
Now how can i ensure that each variable is only taken once but still randomly?
Thank You
Shuffle the array and pop of values instead
function shuffle(a) {
var c=a.length,t,r;
while (0 !== c) {
r = Math.floor(Math.random() * c);
c -= 1;t = a[c];a[c] = a[r];a[r] = t;
}
return a;
}
var thumbnailArray = [
'contentarray1',
'contentarray2',
'contentarray3'
];
shuffle( thumbnailArray );
thumbnailquery();
function thumbnailquery () {
for (var i = 0; i <= 3; i++) {
$('#myDiv').prepend( thumbnailArray.pop() );
}
}
FIDDLE
Copy the array. Then delete objects that you took from the copied array.
There's no elegant way to do it the way you describe. You could construct an array of "selected indices" and ensure that each random number didn't already exist in that array, but that has a worst case operating time of infinity so highly not recommended.
Your best bet would be to shuffle the array and then iterate over, selecting the elements in order (shuffled order).
See this Stack Overflow for a good way to shuffle an array in JavaScript
How can i shuffle an array in JavaScript?
Use splice() http://www.w3schools.com/jsref/jsref_splice.asp
randNum = thumbnailArray[Math.floor(Math.random() * thumbnailArray.length)]
$('#myDiv').prepend(splice(randNum,1))

Generate Array Javascript

I want to generate an array in jQuery/JS, which contains "code"+[0-9] or [a-z].
So it will look like that.
code0, code1 ..., codeA, codeB
The only working way now is to write them manually and I am sure this is a dumb way and there is a way to generate this automatically.
If you give an answer with a reference to some article where I can learn how to do similar stuff, I would be grateful.
Thank you.
For a-z using the ASCII table and the JavaScript fromCharCode() function:
var a = [];
for(var i=97; i<=122; i++)
{
a.push("code" + String.fromCharCode(i));
}
For 0-9:
var a = [];
for(var i=0; i<=9; i++)
{
a.push("code" + i);
}
I'm using the unicode hexcode to loop through the whole symbols from 0-z:
var arr = [];
for (var i = 0x30; i < 0x7b;i++){
// skip non word characters
// without regex, faster, but not as elegant:
// if(i==0x3a){i=0x41}
// if(i==0x5b){i=0x61}
char = String.fromCharCode(i);
while(!/\w/.test(char)){char = String.fromCharCode(i++)};
// generate your code
var res = "code"+char;
// use your result
arr.push(res);
}
console.log(arr);
Here goes your example.
Docs:
Unicode Table
for loop
fromCharCode
JS Array and it's methods
you can generate array in javascript by using following code.
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push("code"+ i);
}
please refer following links.
https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Array
http://www.scriptingmaster.com/javascript/JavaScript-arrays.asp
a = [];
for(i = 48; i < 91; i++) {
if (i==58) i = 65
a.push("code" + String.fromCharCode(i));
}
alert(a.join(',')) // or cou can print to console of browser: console.log(a);

Javascript generate random unique number every time

Ok so i need to create four randomly generated numbers between 1-10 and they cannot be the same. so my thought is to add each number to an array but how can I check to see if the number is in the array, and if it is, re-generate the number and if it isnt add the new number to the array?
so basically it will go,
1.create new number and add to array
2.create second new number, check to see if it exist already, if it doesn't exist, add to array. If it does exist, re-create new number, check again etc...
3.same as above and so on.
You want what is called a 'random grab bag'. Consider you have a 'bag' of numbers, each number is only represented once in this bag. You take the numbers out, at random, for as many as you need.
The problem with some of the other solutions presented here is that they randomly generate the number, and check to see if it was already used. This will take longer and longer to complete (theoretically up to an infinite amount of time) because you are waiting for the random() function to return a value you don't already have (and it doesn't have to do that, it could give you 1-9 forever, but never return 10).
There are a lot of ways to implement a grab-bag type solution, each with varying degrees of cost (though, if done correctly, won't ever be infinite).
The most basic solution to your problem would be the following:
var grabBag = [1,2,3,4,5,6,7,8,9,10];
// randomize order of elements with a sort function that randomly returns -1/0/1
grabBag.sort(function(xx,yy){ return Math.floor(Math.random() * 3) - 1; })
function getNextRandom(){
return grabBag.shift();
};
var originalLength = grabBag.length;
for(var i = 0; i < originalLength; i++){
console.log(getNextRandom());
}
This is of course destructive to the original grabBag array. And I'm not sure how 'truly random' that sort is, but for many applications it could be 'good enough'.
An slightly different approach would be to store all the unused elements in an array, randomly select an index, and then remove the element at that index. The cost here is how frequently you are creating/destroying arrays each time you remove an element.
Here are a couple versions using Matt's grabBag technique:
function getRandoms(numPicks) {
var nums = [1,2,3,4,5,6,7,8,9,10];
var selections = [];
// randomly pick one from the array
for (var i = 0; i < numPicks; i++) {
var index = Math.floor(Math.random() * nums.length);
selections.push(nums[index]);
nums.splice(index, 1);
}
return(selections);
}
You can see it work here: http://jsfiddle.net/jfriend00/b3MF3/.
And, here's a version that lets you pass in the range you want to cover:
function getRandoms(numPicks, low, high) {
var len = high - low + 1;
var nums = new Array(len);
var selections = [], i;
// initialize the array
for (i = 0; i < len; i++) {
nums[i] = i + low;
}
// randomly pick one from the array
for (var i = 0; i < numPicks; i++) {
var index = Math.floor(Math.random() * nums.length);
selections.push(nums[index]);
nums.splice(index, 1);
}
return(selections);
}
And a fiddle for that one: http://jsfiddle.net/jfriend00/UXnGB/
Use an array to see if the number has already been generated.
var randomArr = [], trackingArr = [],
targetCount = 4, currentCount = 0,
min = 1, max = 10,
rnd;
while (currentCount < targetCount) {
rnd = Math.floor(Math.random() * (max - min + 1)) + min;
if (!trackingArr[rnd]) {
trackingArr[rnd] = rnd;
randomArr[currentCount] = rnd;
currentCount += 1;
}
}
alert(randomArr); // Will contain four unique, random numbers between 1 and 10.
Working example: http://jsfiddle.net/FishBasketGordo/J4Ly7/
var a = [];
for (var i = 0; i < 5; i++) {
var r = Math.floor(Math.random()*10) + 1;
if(!(r in a))
a.push(r);
else
i--;
}
That'll do it for you. But be careful. If you make the number of random numbers generated greater than the may number (10) you'll hit an infinite loop.
I'm using a recursive function. The test function pick 6 unique value between 1 and 9.
//test(1, 9, 6);
function test(min, max, nbValue){
var result = recursValue(min, max, nbValue, []);
alert(result);
}
function recursValue(min, max, nbValue, result){
var randomNum = Math.random() * (max-min);
randomNum = Math.round(randomNum) + min;
if(!in_array(randomNum, result)){
result.push(randomNum);
nbValue--;
}
if(nbValue>0){
recursValue(min, max, nbValue, result);
}
return result;
}
function in_array(value, my_array){
for(var i=0;i< my_array.length; i++){
if(my_array[i] == value){
console.log(my_array+" val "+value);
return true;
}
}
return false;
}
Here is a recursive function what are you looking for.
"howMany" parameter is count of how many unique numbers you want to generate.
"randomize" parameter is biggest number that function can generate.
for example : rand(4,8) function returns an array that has 4 number in it, and the numbers are between 0 and 7 ( because as you know, Math.random() function generates numbers starting from zero to [given number - 1])
var array = [];
var isMatch= false;
function rand(howMany, randomize){
if( array.length < howMany){
var r = Math.floor( Math.random() * randomize );
for( var i = 0; i < howMany; i++ ){
if( array[i] !== r ){
isMatch= false;
continue;
} else {
isMatch= true;
break;
}
}
if( isMatch == false ){
array.push(r);
ran(howMany, randomize);
}
ran(howMany, randomize);
return array;
}
}
In your answer earlier, you do have a small bug. Instead of
var originalLength = grabBag.length;
for(var i = 0; i < originalLength .length; i++){
console.log(getNextRandom());
}
I believe you meant:
var originalLength = grabBag.length;
for(var i = 0; i < originalLength; i++){
console.log(getNextRandom());
}
Thanks.

Categories

Resources