My code not works well

I have an code, that picks an random pet from given pets array. The pet’ rarity does have decimals. So, I have to multiply them. But it shouldn’t save it. I don’t know why but its changes given pet array for permanently. The N variable is for my extra luck system. When n = 1, there’s no problem. When is n over 1 there’s problem.

local Multiplier = 1

for _,Pet in Pets do
    local split = string.split(tostring(Pet.Percentage), ".")
    if split[2] ~= nil then
        if 10 ^ string.len(split[2]) > Multiplier then
            Multiplier = 10 ^ string.len(split[2])
        end
    end
end

for _,Pet in Pets do
    local n = 2

    Pet.Percentage = (Pet.Percentage * Multiplier) * n
end

code output:
on first time my pet’ rarity percentage: 800
on second time my pet’ rarity percentage: 1600
on third time my pet’ rarity percentage: 3200

desired output:
on first time my pet’ rarity percentage: 800
on second time my pet’ rarity percentage: 800
on third time my pet’ rarity percentage: 800
… (always same ^)

2 Likes

You are taking the value of the Pet.Percentage equal to 2 times itself. You should change the second Pet.Percentage to a base value, as you have mentioned, 800

Doesn’t work. Value is still getting bigger when N is not equal to 1

Is the output different from the previous every time? If it isn’t then it is painfully obvious that it is multiplying by n.

I am assuming that you are trying to get random element from an array based on percent rarity.
Here more basic code for that.

--Example list of pets
local Pets = {
  {
      Name = "Dog",
      Percent = 40,
  },
  {
      Name = "Cat",
      Percent = 30,
  },
  {
      Name = "Bunny",
      Percent = 20,
  },
  {
      Name = "Fox",
      Percent = 9.5,
  },
  {
      Name = "Bull",
      Percent = 0.5,
  },
}

--The function that you need
function getRandomPet()
    local p = math.random()
    local cumulativeProbability = 0
    for i, Pet in pairs(Pets) do
        cumulativeProbability = cumulativeProbability + (Pet.Percent / 100)
        if p <= cumulativeProbability then
            return Pet
        end
    end
end

--Testing the function
local count = { }

local iterations = 5000000
for i=1,iterations do
    local name = getRandomPet().Name
    count[name] = (count[name] or 0) + 1
end

for name, count in pairs(count) do
    print(name, count/iterations * 100)
end

Note: The total percent of elements must not excess 100

Thanks! I’d better use it. (blablablablablabla)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.