Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add functions to pick a random element from an array #65077

Closed
wants to merge 1 commit into from

Conversation

timothyqiu
Copy link
Member

Revival of #57007
Closes godotengine/godot-proposals#3454

In addition to the original functionality, I decided to also support

  • Picking from packed arrays
    • To keep things simple, I made it a free function that takes any array type (Array, PackedStringArray, etc...) instead of a method on each array type. This also makes it easier to extend later if we want to support picking from more types.
    • To be consistent with functions like randi() and randi_range(), I named the function rand_pick().
  • Using a random number generator
    • A similar rand_pick() method is added to RandomNumberGenerator.
# Regular array
var arr := [1, 2, 3, 4, 5]
print(rand_pick(arr))
print(rand_pick(arr))

# Packed array
print(rand_pick("Mon Tue Wed Thu Fri Sat Sun".split(" ")))

# With RandomNumberGenerator (useful for procedural generation)
var rng := RandomNumberGenerator.new()
rng.state = 2022
print(rng.rand_pick(arr))  # Prints 1
print(rng.rand_pick(arr))  # Prints 2
rng.state = 2022
print(rng.rand_pick(arr))  # Prints 1
print(rng.rand_pick(arr))  # Prints 2

Verified

This commit was signed with the committer’s verified signature.
driesvints Dries Vints
@timothyqiu
Copy link
Member Author

Superseded by #67444

@timothyqiu timothyqiu closed this Nov 16, 2022
@timothyqiu timothyqiu deleted the pick-random branch November 16, 2022 02:11
@akien-mga akien-mga removed this from the 4.x milestone Nov 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add Array.pick_random() as a shorthand for Array[randi() % Array.size()]
2 participants