Просмотр полной версии : вопрос о random
напримкр, если я пишу
random(10);
это значит - случайное число от до 0 до 10.
а как написать, чтобы случайное число было не от 0, а, например, от 5 до 10?
random(10) это 0 - 9
random(11)+5 это 15 - 10
когда на actionscript.org кто-то запостил. Надеюсь перевод не нужен...
Randomly producing 1 or -1
Math.random() > 0.5 ? 1 : -1;
(deprecated syntax: random(2) ? 1 : -1 or (random(2)*2)-1
Randomly producing a number in a range from lo to hi
Math.random()*(hi-lo) + lo
for an integer, Math.floor(Math.random()*(hi-lo) + lo) but this will produce numbers from lo to hi-1, inclusive
Making a bell curve (gaussian distribution, normal distribution)
(Math.random() * x) + (Math.random() * x) or
(Math.random() * x) + (Math.random() * x) + (Math.random() * x) and etc.
Rolling two dice:
trace(Math.floor(6 * Math.random() + 1)+Math.floor(6 * Math.random() + 1));
(Each die can have any of six faces, so produce an integer between 0 and 5 by flooring a multiple of the random. Add "1" because no side of the die has zero spots.)
myRandom from Colin Moock's ASDG
// returns a number in the range minVal to maxVal, inclusive
function myRandom (minVal, maxVal) {
return minVal+Math.floor(Math.random()*(maxVal+1-minVal));
}
//
pickRandom from array with weightings
/*returns an integer in the range of the length of the array supplied as a parameter. The parameter array contains any numbers, indicating a relative weighting or a probability of that index being picked.*/
Math.pickRandom = function(weightings){
var L = weightings.length;
var cumulative = new Array(L);
for(var i=0;i<L;i++){
if(i==0){
cumulative[i] = weightings[i];
}else{
cumulative[i] = weightings[i] + cumulative[i-1];
}
}
var rand = Math.random()*cumulative[L-1];
for(var i=0;i<L;i++){
if(cumulative[i]>=rand){
break;
}
}
return i;
}
//eg
// pick 1,2 or 3, with 3 being twice as likely as the others
rand = Math.pickRandom([0,1,1,2]);
// - Peter Hall
Работает на vBulletin ® версия 3.7.3. Copyright ©2000-2026, Jelsoft Enterprises Ltd. Перевод: zCarot
Copyright © 1999-2008 Flasher.ru. All rights reserved.