Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I get this to sort correctly if the values are the same number?

Asked by 6 years ago

So what the line of code does below is it goes into a model named "SortedTimes" and sorts them based on their values from least to greatest from 1 to 10+. I am trying to get this to check if any of the values are the same number and if they are the same number then I want the code below to change the names of the values to the same name. (Ex 1,1,2,3,4 and so on.) instead of (ex. 1,2,3,4). Can someone help me PLEASE?

local Times = {}
            for _, intValue in pairs(script.SortedTimes:GetChildren()) do
                local inserted = false
                for i, time in pairs(Times) do
                    if intValue.Value < time then 
                        inserted = true
                        table.insert(Times, i, intValue.Value)
                        break
                    end
                end
                if not inserted then
                    table.insert(Times, #Times+1, intValue.Value)
                end
            end
            local intValues = script.SortedTimes:GetChildren()

            for i, time in pairs(Times) do
                for intValueKey, intValue in pairs(intValues) do
                    if time == intValue.Value then
                        intValue.Name = i
                        table.remove(intValues, intValueKey)
                        break
                    end
                end
            end
1
Thanks for the help. Useless community... -.- billybobtijoseph 1 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago

If you don't need to maintain a sorted list, you can just use a dictionary to keep track of how many of each number you have:

local count = {}
function AddToCount(num)
    count[num] = (count[num] or 0) + 1
end
function RemoveFromCount(num)
    count[num] = count[num] > 1 and count[num] - 1 or nil
end
function GetCount(num)
    return count[num] or 0
end

--example usage:

AddToCount(3)
AddToCount(3)
print(GetCount(3)) -- 2
Ad

Answer this question