Files
esengine/source/src/Utils/RandomUtils.ts

134 lines
3.9 KiB
TypeScript
Raw Normal View History

class RandomUtils {
/**
* start stop之间取一个随机整数step指定间隔 start与stop较大的一个
*
* this.randrange(1, 10, 3)
* 1 4 7 , 1010
*
* @param start
* @param stop
* @param step
* @return start < stop, [start, stop)
*
*/
public static randrange(start: number, stop: number, step: number = 1): number {
if (step == 0)
throw new Error('step 不能为 0');
let width: number = stop - start;
if (width == 0)
throw new Error('没有可用的范围(' + start + ',' + stop + ')');
if (width < 0)
width = start - stop;
let n: number = Math.floor((width + step - 1) / step);
return Math.floor(this.random() * n) * step + Math.min(start, stop);
}
/**
* a b直间的随机整数 a b
* @param a
* @param b
* @return [a, b]
*
*/
public static randint(a: number, b: number): number {
a = Math.floor(a);
b = Math.floor(b);
if (a > b)
a++;
else
b++;
return this.randrange(a, b);
}
/**
* a - b之间的随机数 Math.max(a, b)
* @param a
* @param b
* @return a < b, [a, b)
*/
public static randnum(a: number, b: number): number {
return this.random() * (b - a) + a;
}
/**
*
* @param array
* @return
*/
public static shuffle(array: any[]): any[] {
array.sort(this._randomCompare);
return array;
}
private static _randomCompare(a: Object, b: Object): number {
return (this.random() > .5) ? 1 : -1;
}
/**
*
* @param sequence vectorlength属性
*
* @return
*
*/
public static choice(sequence: any): any {
if (!sequence.hasOwnProperty("length"))
throw new Error('无法对此对象执行此操作');
let index: number = Math.floor(this.random() * sequence.length);
if (sequence instanceof String)
return String(sequence).charAt(index);
else
return sequence[index];
}
/**
* æ ?
* <pre>
* this.sample([1, 2, 3, 4, 5], 3) // Choose 3 elements
* [4, 1, 5]
* </pre>
* @param sequence
* @param num
* @return
*
*/
public static sample(sequence: any[], num: number): any[] {
let len: number = sequence.length;
if (num <= 0 || len < num)
throw new Error("采样数量不够");
let selected: any[] = [];
let indices: any[] = [];
for (let i: number = 0; i < num; i++) {
let index: number = Math.floor(this.random() * len);
while (indices.indexOf(index) >= 0)
index = Math.floor(this.random() * len);
selected.push(sequence[index]);
indices.push(index);
}
return selected;
}
/**
* 0.0 - 1.0 Math.random()
* @return Math.random()
*
*/
public static random(): number {
return Math.random();
}
/**
*
* @param chance
* @return
*/
public static boolean(chance: number = .5): boolean {
return (this.random() < chance) ? true : false;
}
}