# P5.js choosing randomly from an array of functions

**URL:** <https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666>\
**Category:** Coding Questions\
**Created:** [November 22, 2021, 1:31pm UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666 "2021-11-22T13:31:48Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![okkobroderson](https://avatars.discourse-cdn.com/v4/letter/o/22d042/32.png) [@okkobroderson](https://discourse.processing.org/u/okkobroderson)\
**Post date:** [November 22, 2021, 1:31pm UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/1 "2021-11-22T13:31:48Z")

</div>

hi, first post!  
i have declared an array of functions like

```auto
funx = [func1, func2, ...];

```

in the draw loop i want to call theese randomly like

```auto
funx[random(funx)]();

```

it works when i call the functions by index like

```auto
funx[0]();

```

would need some help to accomplish this.  
thanks

---

<div class="post-metadata">

**Author:** ![javagar](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/javagar/32/11434_2.png) [@javagar](https://discourse.processing.org/u/javagar)\
**Post date:** [November 22, 2021, 2:04pm UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/2 "2021-11-22T14:04:21Z")

</div>

Hello, @okkobroderson, and welcome to the Processing Forum!

For starters, try this:

```auto
// define three functions.
function func1() {
  background(255, 0, 0);
}

function func2() {
  background(0, 255, 0);
}

function func3() {
  background(0, 0, 255);
}

let funcs = [func1, func2, func3];

function setup() {
  frameRate(2); // slow frame rate.
}

function draw() {
  random(funcs)(); // during each frame, select a function randomly and call it.
}

```

---

<div class="post-metadata">

**Author:** ![okkobroderson](https://avatars.discourse-cdn.com/v4/letter/o/22d042/32.png) [@okkobroderson](https://discourse.processing.org/u/okkobroderson)\
**Post date:** [November 22, 2021, 2:15pm UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/3 "2021-11-22T14:15:27Z")

</div>

thank you very much @javagar

```auto
random(funcs)();

```

did the trick:)

---

<div class="post-metadata">

**Author:** ![javagar](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/javagar/32/11434_2.png) [@javagar](https://discourse.processing.org/u/javagar)\
**Post date:** [November 22, 2021, 2:18pm UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/4 "2021-11-22T14:18:59Z")

</div>

Yes, and you can pass an argument to the selected function, as follows, provided that the function was defined to accept an argument:

```auto
  random(funcs)(frameCount);

```

---

<div class="post-metadata">

**Author:** ![okkobroderson](https://avatars.discourse-cdn.com/v4/letter/o/22d042/32.png) [@okkobroderson](https://discourse.processing.org/u/okkobroderson)\
**Post date:** [November 22, 2021, 5:58pm UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/5 "2021-11-22T17:58:21Z")

</div>

ah, that’s good to know!  
opens up some more possibilities…

…but also brings up more qustions.  
in case the different functions require different sets of arguments.  
how can we know about which function was picked by random(funcs), to provide the right arguments?

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [November 22, 2021, 6:56pm UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/6 "2021-11-22T18:56:55Z")

</div>

> [@okkobroderson](#):
>
> , to provide the right arguments?

> **[Function: length - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length)**
>
> The length data property of a Function instance indicates the number of parameters expected by the function.

---

<div class="post-metadata">

**Author:** ![javagar](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/javagar/32/11434_2.png) [@javagar](https://discourse.processing.org/u/javagar)\
**Post date:** [November 22, 2021, 9:59pm UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/7 "2021-11-22T21:59:28Z")

</div>

> [@okkobroderson](#):
>
> … in case the different functions require different sets of arguments. …

Another possibility, especially if the functions require various combinations of numbers and types of arguments, is to create an object, with the names of the functions as strings that serve as keys, and the types of arguments, as Arrays of strings associated with each key. Then choose randomly from the keys in the object, and use the Array of argument types associated with that key to assemble an appropriate function call. It may be complicated, but it could be fun. 🙂

_EDIT (2x on November 22, 2021):_

For yet another strategy, try the code below. It randomly chooses functions paired with their arguments.

```auto
// three functions that draw shapes
function rect_maker(x, y, r, g, b) {
  fill(r, g, b);
  rect(x, y, 40, 40);
}

function ellipse_maker(x, y, w, h) {
  fill(random(256), random(256), random(256), random(256));
  ellipse(x, y, w, h);
}

function line_maker() {
  line(random(width), random(height), random(width), random(height));
}

function setup() {
  createCanvas(240, 240);
  strokeWeight(4);
  stroke(0);
  frameRate(1);
  rectMode(CENTER);
}

function draw() {
  // array of arrays of functions with randomly-valued arguments for each
  let funcs_and_args = [
                        [rect_maker, [random(width), random(height), random(256), random(256), random(256)]],
                        [ellipse_maker, [random(width), random(height),random(width / 4), random(height / 4)]],
                        [line_maker, []]
                       ];
  // randomly choose a function with arguments pair
  let f_and_a = random(funcs_and_args);
  // call the chosen function, passing its arguments to it; use destructuring
  f_and_a[0](...f_and_a[1]);
}

```

![funcs_with_args](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/e/eaff6299216b723f44d8881b3b9bf7fd1f5da866.png)

To understand this line …

```auto
  f_and_a[0](...f_and_a[1]);

```

… see …

> **[Destructuring assignment - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)**
>
> The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

---

<div class="post-metadata">

**Author:** ![okkobroderson](https://avatars.discourse-cdn.com/v4/letter/o/22d042/32.png) [@okkobroderson](https://discourse.processing.org/u/okkobroderson)\
**Post date:** [November 23, 2021, 10:01am UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/8 "2021-11-23T10:01:56Z")

</div>

thanks you! @GoToLoop

---

<div class="post-metadata">

**Author:** ![okkobroderson](https://avatars.discourse-cdn.com/v4/letter/o/22d042/32.png) [@okkobroderson](https://discourse.processing.org/u/okkobroderson)\
**Post date:** [November 23, 2021, 10:05am UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/9 "2021-11-23T10:05:52Z")

</div>

wow, that’s cool!  
thank you very much for your efforts @javagar

that should provide enough fun for long winter evenings:)

---

<div class="post-metadata">

**Author:** ![javagar](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/javagar/32/11434_2.png) [@javagar](https://discourse.processing.org/u/javagar)\
**Post date:** [November 23, 2021, 7:19pm UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/10 "2021-11-23T19:19:39Z")

</div>

Below is another scheme that utilizes an array of anonymous functions, each of which calls one of the named functions with a set of required arguments.

This pattern may be easy to revise and maintain, since adding a new function call to the array merely requires copying one of the existing elements of the array and applying some modifications. It would also be simple to add a new named function by defining it, and then by following one of the existing patterns in the array to add an appropriate function call.

p5.js Code:

```auto
// three named shape maker functions with various numbers of arguments
function rect_maker(x, y, r, g, b) {
  fill(r, g, b, 128);
  rect(x, y, random(20, 40), random(20, 40));
}

function ellipse_maker(x, y, w, h) {
  fill(random(256), random(256), random(256), random(256));
  ellipse(x, y, w, h);
}

function triangle_maker() {
  fill(random(256), random(256), random(256), 16);
  triangle(random(width), random(height), random(width), random(height), random(width), random(height));
}

// array of anonymous functions, each of which can call one of the above named functions
let function_runners = [
  () => {rect_maker(random(width), random(height), random(256), random(256), random(256));},
  () => {ellipse_maker(random(width), random(height),random(width / 4), random(height / 4));},
  () => {triangle_maker();}
];

function setup() {
  createCanvas(200, 200);
  noStroke();
  frameRate(1);
  rectMode(CENTER);
  background(240);
}

function draw() {
  // randomly choose and execute a function with arguments
  random(function_runners)();
}

```

Image:

![rfwa](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/8/8f639d61e51061b76472e68c193bfaec9c826243.png)

_Edited on November 23, 2021 to revise some of the explanatory text._

---

<div class="post-metadata">

**Author:** ![okkobroderson](https://avatars.discourse-cdn.com/v4/letter/o/22d042/32.png) [@okkobroderson](https://discourse.processing.org/u/okkobroderson)\
**Post date:** [November 24, 2021, 7:09pm UTC](https://discourse.processing.org/t/p5-js-choosing-randomly-from-an-array-of-functions/33666/11 "2021-11-24T19:09:22Z")

</div>

thank’s again for this new approach @javagar.  
indeed it seems easy to maintain and extend with new ideas for functions.

greetings
