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
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);
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]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.