-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshuffleBag.lua
More file actions
40 lines (32 loc) · 768 Bytes
/
shuffleBag.lua
File metadata and controls
40 lines (32 loc) · 768 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
local ShuffleBag = {}
ShuffleBag.__index = ShuffleBag
local random <const> = math.random
local function copy(tab)
local dest = {}
for i = 1, #tab do
dest[i] = tab[i]
end
return dest
end
function ShuffleBag.new(items)
local self = setmetatable({}, ShuffleBag)
self.items = copy(items)
self.total = #self.items
self.pivot = 1
return self
end
function ShuffleBag:take()
local items = self.items
local pivot = self.pivot
local total = self.total
local ix = random(pivot, total)
local value = items[ix]
items[ix] = items[pivot]
items[pivot] = value
self.pivot = (pivot < total) and (pivot + 1) or 1
return value
end
function ShuffleBag:reset()
self.pivot = 1
end
return ShuffleBag