# Optimize a way to pair Players?

I want to create a script that sorts a table into duos with players but I don’t know how I could make the code effiecent and not “clunky”. So like for an example:

``````local Contestants = {1,2,3,4,5,6,7,8}

local Teams = {{1,2}, {3,4}, {5,6}, {7,8}}
``````

Something in that order, NOT RANDOM, so that p1 pairs with p2… p3 pairs with p4.
Thanks for the help.

1 Like

I think you would have to assign a number to every player when they join, after that make the script pair them up, something like:

``````local newPlayer = Players.PlayerAdded
local copy = instance.new(“IDon’tRememberWhatIsCalled :rofl:”)
copy.Parent = NewPlayer
—Here you would get the table and and assign the number
``````
1 Like

The code makes no sense aswell as the response to the context, def used ChatGPT or is a new programmer. Fixed it by usuing a simple algorithm for any future reference. Although its primitive and leaves out an odd last index. (Good for my case, might be bad for y’all).

``````local Offset = 0
for Player= 1,math.floor(#Players/2) do
print(Players[1+Offset],Players[2+Offset],1+Offset,2+Offset)
Offset += 2
end
``````
2 Likes

I’m a new programmer but what I meant basically is, get the player that joins, assign him a number create a table with the numbers and then pair player 1 with player 2 etc.

I know you already solved this, but here’s a way I personally think would work better for you so there aren’t as many magic numbers floating around

``````local Contestants = {1,2,3,4,5,6,7,8}
local Teams = {}

for i,v in next, Contestants do
if i % 2 == 1 then -- Player index is an odd number, make a new table
table.insert(Teams, {v})
else
table.insert(Teams[i / 2], v) -- Player index is an even number, add player to current table
end
end
``````

This still leaves out the 1 player if contestants are uneven

1 Like

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