is there any way to put a percentage to each randomize object

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By RubRub

What I want is that each text has a percentage of appearing but I don’t know how to implement it

(This is the code made in gdscript)

(Sorry for the words in Spanish is that I am Mexican xd)

extends Node2D

var Texto = [“Hola”, “Como estas?”, “Secret”, “Mi nombre real es …”, “Si llegas a 100 puntos te dare una recompenza”]

func _ready():
pass

func _on_Button_pressed():
$Label.text = Texto[randi() % len(Texto)]

:bust_in_silhouette: Reply From: Inces

If You use “%” in code it doesn’t mean percent, but modulo - rest from division of one integer by the other.

You can achive your goal like this :

var rand = RandomNumberGenerator.new()
var index = rand.randi_range(Texto.size()-1)
$Label.text = Texto[index]

I think they want weighted percentages and not each item having the same percentage of appearing.

exuin | 2021-10-26 16:51

exactly :smiley:

I mean which example “Hello” has 40% to appear or “Secret” It has 10% to appear, I don’t know if you understand me

RubRub | 2021-10-26 16:53

:bust_in_silhouette: Reply From: exuin

Do something like this:

var percentages = [0.1, 0.2, 0.3, 0.3, 0.1] # This should add to 1.0!
# ...
var num = randf()
var total = 0.0
var count = 0
for per in percentages:
    if num >= total and num <= total + per:
        $Label.text = Texto[count]
        break
    total += per
    count += 1

Where is the variable called “Percentage”, is it literally the same or is that where the variable “texto” that I add goes?

RubRub | 2021-10-26 16:47

It should be a new variable, not texto.

exuin | 2021-10-26 16:51

Ah I already understood the code, it is an implementation of the code I had, Thank you but there where it says percentages it is giving you some percentages, but I want each word to have a specific percentage such as “Secret” having 40%.

RubRub | 2021-10-26 16:59

Yeah, so put 0.4 in the same index as “Secret”.

exuin | 2021-10-26 17:05

Something like Text = [“Hello” 0.4, “Bye” 0.3]

RubRub | 2021-10-26 17:31

No, you need two separate arrays.

exuin | 2021-10-26 18:02

then how would it be ?, can you give me a reference code pls?

RubRub | 2021-10-26 18:03

I already gave you the code.

exuin | 2021-10-26 18:19

Ah if I mean the one with the two separate matrices, I did not understand that very well

RubRub | 2021-10-26 18:21

You need two arrays, one to hold the strings and one to hold the percentages.

exuin | 2021-10-26 21:50