Independent random generations in Javascript / p5.js

冷暖自知 提交于 2020-05-24 07:29:31

问题


In P5.js, I often have to write more than one line of random in order to get independent random generation such as :

random();
random();
random();

// or 
a = random();
b = random();
c = random();

//etc

is there any alternative code(s) in p5.js or javascript that can perform the same/similar generations and so the code efficiency can be improve? Thanks


回答1:


If you're putting random numbers into an array, you can do it concisely with Array.from:

const random = () => Math.random();

const arr = Array.from({ length: 3 }, random);
console.log(arr);

You can do the same sort of thing for multiple separate variables by destructuring:

const random = () => Math.random();

const [a, b, c] = Array.from({ length: 3 }, random);
console.log(a);
console.log(b);
console.log(c);

If you need to call random with certain parameters, then:

const random = (low, high) => Math.floor((high - low) * Math.random()) + low;

const [a, b, c] = Array.from({ length: 3 }, () => random(1, 4));
console.log(a);
console.log(b);
console.log(c);



回答2:


If you would rather not perform random calculations within draw() then you could generate an array of pre-calculated random numbers in setup. When you need a random number you just grab one from the array.

let rndListLength = 100;
let rndNums;

function setup() {  
  rndNums = [...Array(rndListLength).keys()].map(a => random());

  // Show complete list
  console.log(rndNums);

  // Show number 17 in list 
  // (remember the first array index is always 0)
  console.log(rndNums[16]);
}


来源:https://stackoverflow.com/questions/61333828/independent-random-generations-in-javascript-p5-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!