Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript/jquery random number between -13 and 13 excluding numbers between -3 and 3

I am using

var min = -13;
var max = 13;
var random = Math.floor(Math.random() * (max - min + 1)) + min;

but it returns ALL numbers(random) between -13 and 13. how can i get it to generate a random number between -13 to -4 exluding -3 , -2, -1, 0 , 1 ,2 ,3 and including 4 to 13.

like image 797
Yusaf Khaliq Avatar asked Feb 16 '12 12:02

Yusaf Khaliq


3 Answers

Get a random number between 1-10 and add 3, to get one between 4-13:

random = Math.ceil(Math.random() * 10) + 3;

Generate a random between 0-1. If it's 0, make the number negative:

random = (Math.floor(Math.random() * 2) == 0) ? 0 - random : random;

JSFiddle showing working copy:

http://jsfiddle.net/adamh/cyGwf/

like image 165
Adam Hopkinson Avatar answered Nov 19 '22 21:11

Adam Hopkinson


var pickOne = [4,5,6,7,8,9,10,11,12,13],
    value   = pickOne[Math.floor(Math.random() * pickOne.length)];

value   = (Math.random() < 0.5)? value : -value;
console.log(value)
like image 1
Fabrizio Calderan Avatar answered Nov 19 '22 23:11

Fabrizio Calderan


Minor tweak to what you have should do it. Produce a random in the range of -6 to 13, and then if the value is less than 4, subtract 7. I have not tested it, but I suspect it would perform better than producing two randoms and multiplying.

var min = -6; 
var max = 13; 
var random = Math.floor(Math.random() * (max - min + 1)) + min; 
if(random < 4){random = random - 7;}
like image 1
Rozwel Avatar answered Nov 19 '22 21:11

Rozwel