# Source URL: https://dev.epicgames.com/community/snippets/N04/fortnite-random-permutation-picker-device
# Local doc: epic-docs/community/snippets/N04/fortnite-random-permutation-picker-device.md
using { /Fortnite.com/Devices }
using { /Verse.org/Random }
using { /Verse.org/Simulation }
using { /UnrealEngine.com/Temporary/Diagnostics }
# The random_permutation_picker device generates a random permutation of
# its Choices and then picks them one at a time, without item repetition, with Pick.
# When the last choice has been picked, a new permutation is generated.
random_permutation_picker_device := class(creative_device):
@editable
PickButton:button_device = button_device{}
# The Choices array is the set of elements to be picked.
@editable
var<private> Choices:[]switch_device = array{}
var<private> PickStartIndex<private>:int=0
# Pick one of the Choices, without repetition.
# The algorithm uses a form of the Fisher-Yates shuffle to generate a random permutation.
# See https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
# for a description of the Fisher-Yates shuffle algorithm.
Pick<public>()<transacts><decides>:switch_device=
# Imagine a hat with all the Choices in it.
# The hat is full at the start of the permutation.
# PickStartIndex is the index of the first element in the hat.
# We pick an element from the hat, remove it from the hat, and return it.
# When the hat is empty, we refill it and start a new permutation.
# Generate a random integer between PickStartIndex and Choices.Length-1, inclusive.
# This is the index of the element to be picked.
PickedIndex := GetRandomInt(PickStartIndex, Choices.Length-1)
# Select the element at PickedIndex. We'll swap it with the element at PickStartIndex and return it.
Verse Library
verse
01 Snippet
Selects random items from an array without repetition using Fisher-Yates shuffling.
extracted-snippets/community/snippets/N04/fortnite-random-permutation-picker-device/01-snippet.verse
Sign in free to read the full source 🌴
This Verse Library file is members-only. Create a free account to view the complete source and download the .verse file.