Last active
September 21, 2018 11:16
-
-
Save pallove/dc4007ee89e460a596bc75fb54c13999 to your computer and use it in GitHub Desktop.
随机填充25个数到9*9格子,并且保证每行不少于一个数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local function gen() | |
local arr = {} | |
for i = 1, 9 * 9 do | |
arr[i] = i > 25 and 0 or i | |
end | |
return arr | |
end | |
local function pr(arr) | |
local r = {} | |
local ck = 0 | |
for k, v in ipairs(arr) do | |
table.insert(r, v) | |
ck = ck + v | |
if (k % 9 == 0) then | |
print(table.concat(r, ',')) | |
assert(ck ~= 0) | |
ck = 0 | |
r = {} | |
end | |
end | |
end | |
local function shuffle(arr) | |
local idx = {} | |
local line = {} | |
for i = 1, 9 do | |
line[i] = 0 | |
end | |
math.randomseed(os.time()) | |
for _ = 1, #arr do | |
local r1 = math.random(#arr) | |
local r2 = math.random(#arr) | |
arr[r1], arr[r2] = arr[r2], arr[r1] | |
if arr[r1] > 0 then | |
idx[arr[r1]] = r1 | |
end | |
if arr[r2] > 0 then | |
idx[arr[r2]] = r2 | |
end | |
end | |
for k, v in pairs(idx) do | |
local n = math.ceil(v / 9) | |
line[n] = line[n] + 1 | |
end | |
local nv, nk = next(idx) | |
for i, v in ipairs(line) do | |
if v == 0 then | |
while math.ceil(nk / 9) == i do | |
nv, nk = next(idx, nv) | |
end | |
local n = (i - 1) * 9 + math.random(9) + 1 | |
arr[n] = nv | |
arr[nk] = 0 | |
end | |
end | |
end | |
local arr = gen() | |
shuffle(arr) | |
pr(arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment