為了這個問題,我將所有網格索引、頂點或其他點稱為點。 所以 (1, 1) 是網格上的一個點,例如。
我正在尋找網格中最小的總大小索引。在這種情況下,(1, 1) 的總和為 2,(2, 1) 的總和為 3,對于 (1, 2) 也是如此。
預期結果:
{ X = 1, Y = 1 }
{ X = 2, Y = 1 }
{ X = 1, Y = 2 }
{ X = 2, Y = 2 }
{ X = 3, Y = 1 }
{ X = 3, Y = 2 }
{ X = 1, Y = 3 }
{ X = 2, Y = 3 }
{ X = 3, Y = 3 }
實際結果:
{ X = 1, Y = 1 }
{ X = 2, Y = 1 }
{ X = 1, Y = 2 }
{ X = 2, Y = 2 }
{ X = 3, Y = 2 }
{ X = 2, Y = 3 }
{ X = 3, Y = 3 }
{ X = 4, Y = 3 }
{ X = 3, Y = 4 }
代碼:
local chunks = {}
local previous = {
X = 0,
Y = 0
}
local largest = {
X = 0,
Y = 0
}
local function addScene()
local new = {
X = (previous.X > previous.Y and previous.Y) or previous.X 1,
Y = (previous.X > previous.Y and previous.X) or previous.Y
}
if new.X == 0 then
new.X = 1
end
if new.Y == 0 then
new.Y = 1
end
largest.X = math.max(largest.X, new.X)
largest.Y = math.max(largest.Y, new.Y)
previous.X = new.X
previous.Y = new.Y
table.insert(chunks, new)
return new
end
for i = 1, 3*3, 1 do
local scene = addScene()
print(i, "(" .. tostring(scene.X) .. ", " .. tostring(scene.Y) .. ")" .. "\n")
end
為自己測驗
如上所示,此代碼非常接近我希望它執行的操作,但只能達到一定程度,并且必須在越來越大的網格中進行擴展。
uj5u.com熱心網友回復:
盡管很可能效率低下,但這最終會產生接近預期的結果。無論如何,您可以簡單地重新組織表格以使其與我在問題中顯示的完全一樣。
local MAX_SIZE = {
X = 3,
Y = 3
}
local chunks = {}
local previous = {
X = 0,
Y = 0
}
local function addScene()
local least = MAX_SIZE.X MAX_SIZE.Y
local new = {
X = 0,
Y = 0
}
for x = MAX_SIZE.X, 1, -1 do
for y = MAX_SIZE.Y, 1, -1 do
if chunks[tostring(x) .. '-' .. tostring(y)] then
break
end
if x ~= 0 and y ~= 0 and x y <= least then
least = x y
new.X = x
new.Y = y
end
end
end
if new.X == 0 then
new.X = 1
end
if new.Y == 0 then
new.Y = 1
end
previous.X = new.X
previous.Y = new.Y
chunks[tostring(new.X) .. '-' .. tostring(new.Y)] = new
return new
end
for i = 1, 3*3, 1 do
local scene = addScene()
print(i, "(" .. tostring(scene.X) .. ", " .. tostring(scene.Y) .. ")" .. "\n")
end
試試看
結果:
1 (1, 1)
2 (1, 2)
3 (2, 1)
4 (1, 3)
5 (2, 2)
6 (3, 1)
7 (2, 3)
8 (3, 2)
9 (3, 3)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/520219.html
上一篇:如何計算BST中的預期葉子數?
