How can I select a random variable from an array?

Get help using Construct 2

Post » Thu May 10, 2012 2:55 pm

Can someone please help me with the following?

I would like to know how to select a random Instance variable stored in an array.SPX2012-05-10 14:56:28
B
8
S
3
G
4
Posts: 8
Reputation: 2,544

Post » Thu May 10, 2012 6:00 pm

If the array is 1d and has the length 10 ...

Set value --> arrayname.At(int(random(10)))
10 can be changed to the array size/length expression..
B
14
S
6
G
5
Posts: 173
Reputation: 4,742

Post » Thu May 10, 2012 6:00 pm

array.at(floor(random(array.width)),floor(random(array.height)))

This get the value from a randon cell in the array... Is that what you want?
B
90
S
30
G
24
Posts: 3,189
Reputation: 32,400

Post » Thu May 10, 2012 6:42 pm

Joe7 showed how to handle a 1 dimensional array. Sqiddster showed how to handle a 2 dimensional array. Here is an example that also handles a three dimensional array.

Actually, it has 3 arrays: one dimension, two dimension, and three dimension. It loops through all dimensions of the arrays inserting a number into each "cell" and then when the mouse is clicked, retrieves a value from a random "cell" in each array.

GetRandomArrayValues.capx
B
29
S
11
G
12
Posts: 281
Reputation: 11,878

Post » Fri May 11, 2012 8:11 am

Thank you for your replies. It's a 1d array do I will use Joe7's answer.

Thans staan!
B
8
S
3
G
4
Posts: 8
Reputation: 2,544

Post » Wed Feb 25, 2015 12:26 am

If I have a 2 dimensional array that stores 0s and 1s, how can I pick random 1?
B
6
S
2
Posts: 24
Reputation: 531

Post » Wed Feb 25, 2015 12:57 am

See the first answer above.
B
24
S
9
G
4
Posts: 1,646
Reputation: 6,596

Post » Wed Feb 25, 2015 1:07 am

Umh, I get a random cell. But what I want is a random cell from the cells that contain value "1".

I tried just picking random cells and see if it contains value 1 or not, but since it is in "while" loop and does not get 1, it goes nuts and crashes.
B
6
S
2
Posts: 24
Reputation: 531

Post » Wed Feb 25, 2015 1:14 am

Ah.. I was going to ask if you want a 'random one' or a 'random 1' :)

You could loop through the array, and when you have a '1' you add the array index to a temporary array. Then use the above method on that array to get an index into the first array.
choose_random_1.capx
You do not have the required permissions to view the files attached to this post.
B
24
S
9
G
4
Posts: 1,646
Reputation: 6,596

Post » Tue Jul 12, 2016 6:42 pm

What if you want to select a random element, but don't know what the length of the array is?
B
16
S
6
Posts: 46
Reputation: 1,194

Next

Return to How do I....?

Who is online

Users browsing this forum: Zakeru and 24 guests