Outputting multiple items randomly from array

Hello everyone, I was wondering how we can output multiple items randomly from an array depending on an input and button, for ex: when we put 3 in the input and click on the button we display 3 random items on the screen, when we put 5 we get 5 etc, thanks !

Hi @Dadci_Raouf - thanks for posting here :slight_smile:

Are duplicate items OK? Or should the items be unique?

1 Like

Hi @kirupa thanks for your feedback
The items should be unique yes with unique ID, for example you have a recipe blog, and you ask the user how many meals he wants to cook when he type 3 in the input you show him 3 random recipes !

1 Like

Hi @Dadci_Raouf. So we want to get N random recipes from our array where N is the value that users type into an input field.

I actually am curious as to the best way to do this because as I was writing out my answer, I realized that my strategy could have an infinite loop (hypothetically).

My original strategy was to keep an array of IDs we have already seen and iterate through it whenever we are trying to find a random recipe; however, once this additional array of IDs get sufficiently big enough, it would 1) be a pain to traverse through so many items and 2) hypothetically, the program could run forever if it continuously spit out a random recipe that we had already seen.

2 Likes

One approach that would work is what I have described here: Picking a Random Item from an Array - #3 by kirupa

:grinning:

1 Like

Yes, the trick it can be not random, but the user will always have the same recipe or make the output random each time he chose the number and click the button.

Did my earlier suggestion help, or are you still looking for some guidance? :slight_smile:

1 Like

Hey :wave: yes, but it’s more complicated,
I decided to use a search bar instead, thank you so much :raised_hands:t3:

1 Like