Discord
Login
Community
DARK THEME

How to shuffle a list

Just shuffle a list, randomize where the stuff is in the list

I did not test this, but this should work:

function shuffleList(list)
  return list.sortList(function()
    return (random.next()*2)-1
  end
end

I use this

//Fisher-Yates shuffle algorithm (in place shuffle)

List.shuffle = function()

  for iSource = this.length - 1 to 0 by -1
    local iDest = random.nextInt(iSource + 1)
    local swap = this[iDest]
    this[iDest] = this[iSource]
    this[iSource] = swap
  end
end

So I can do

data = [0,1,2]
print(data)
data.shuffle()
print(data)

Thanks for the code @HomineLudens

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community