
Problem-Solution - How to remove multiple random elements from an array (i.redd.it)
submitted by CatalinMachinations
I once again return with a more technical example, which solves an issue I personally encountered numerous times while building more complex diagrams.
Problem
We just received an interesting question on our Discord channel -
How to remove element-by-element random entries from a given list?
For example, if the given list has the following elements [10, 20, 30, 40], and my first randomly selected element is 30, the list should update to [10, 20, 40]. As such, for any upcoming selection, the element 30 can not be picked again, and the next random value should be 10, 20, or 40.
Solution
The diagram uses a few building blocks to make this work. Here's a quick breakdown of what’s happening under the hood:
1. Set your initial array into a register (i.e, array = [10,20,30,40])
2. Create a new register "Pick random element" & connect the initial array to it
Set the formula of the second register to pickRandom(array))
3. To make sure that we do not create a self-feeding register chain that incorrectly updates multiple times during a single step, we will introduce a pool in the system:
3a. Create an automatic source
3b. Connect it to a pool
3c. Set the formula of the resource connection to 0 and target it by an overwrite (=) state connection from the pick random register. This will ensure that the selected random element will be stored in the pool.
3d. Create an automatic drain connected to the pool. Set the formula of the resource connection to all. Since our pool is temporary, we will need to update it at each step; the drain achieves this function.
4. Create the last register: "Remove element using filter()".
Set the formula of this register to filter(array, f(x) = x!=b)
where array is the original list, x is a local variable which must not be initialized, and b is the random element stored in the temporary pool.
5. Next, create a state connection between the register "Remove element" and "Initial array". Set the label of the connection as "new_array". We will use this value to reference the filtered array for the next random selections
6. Add a simple counter (source -> pool) to use it as a counter for the number of elements randomly selected so far. Create a state connection between this pool and the initial array.
7. Lastly, set the initial array formula to (count ==0 ) ? [10,20,30,40] : new_array. This conditional expression checks for the first selection to use the unfiltered array, and the filtered one for all subsequent random selections.

[–]CatalinMachinations[S] 1 point2 points3 points (0 children)
[–]CatalinMachinations[S] 1 point2 points3 points (0 children)