簡體   English   中英

尋找一種更有效的方法來描述網格矩形,以便機器人可以觸摸矩形內的每個點

[英]looking for a more efficient method of describing a gridded rectangle so a robot can touch each point inside the rectangle

我一直在嘗試編寫一個解決方案,讓機器人接觸正方形或矩形網格上的每個點。

到目前為止,我一直在研究一個從左下角開始向中心旋轉的螺旋解決方案,我已經讓它工作了,它似乎可以在均勻(正方形)或不均勻(矩形)網格上工作。

我想知道這是否比我在下面的代碼更有效或更優雅的解決方案?

我對編碼很陌生,我希望得到一些關於如何改進此代碼的反饋,或者我是否缺少更簡單的數學解決方案等。

例如:一個 5 x 5 的網格和 [S] 是起始 position 螺旋向 position 25

[05][06][07][08][09]
[04][19][20][21][10]
[03][18][25][22][11]
[02][17][24][23][12]
[01][16][15][14][13]
[st]

目前我的代碼看起來像這樣並且工作正常。 它不需要是一個螺旋,它只是代碼當前的工作方式。

function MoveSides(depth, width) 
    local moving = true
    -- first set of instructions are set as variables and are updated after outer grid is touched
    local leftSide = depth -- for the first side turtle travels to full depth 
    local top = width - 1 -- turns and travels full width -1 as it is sitting on the first row
    local rightSide = depth -1 -- turns and does same coming back on depth
    local bottom = width -2 -- turns and travels width -2 having touched first and last space already

    while moving do
        for i = 1, leftSide do
    turtle.forward() -- move forward one space
        end
    turtle.turnRight()

        for i = 1, top do
    turtle.forward()
        end
    turtle.turnRight()

        for i = 1, rightSide do
    turtle.forward()
        end
    turtle.turnRight()

        for i = 1, bottom do
    turtle.forward()
        end
    turtle.turnRight()

    -- all sides loose 2 as the outers spaces have all been touched to describe next tier of grid.
    leftSide = leftSide -2
    top = top -2
    rightSide = rightSide -2
    bottom = bottom -2

        if (leftSide <= 0 and top <= 0 and rightSide <= 0 and bottom <= 0) then
    moving = false
        end

    end

end

任何幫助或建設性的批評將不勝感激。

如果你想觸摸網格中的每個點,沒有什么比從一個點移動到另一個點更有效的了,每個點只觸摸一次。 這就是你正在做的事情。

您可以以螺旋或行或列方式或混合方式進行操作。 沒關系,因為運動的次數總是相同的。

唯一的區別是你的終點在哪里。

function MoveSides(depth, width) 
   for i = 1, depth do
      turtle.forward() -- move forward one space
   end
   turtle.turnRight()
   if width > 1 then
      return MoveSides(width - 1, depth) 
   end
end
function MoveSides(depth, width) 
  current = depth
  other = width
  while current > 1 do
    for i = 1, current do
      turtle.forward()
    end
    turtle.turnRight()
    helper = current 
    current = other -1
    other = helper
  end
end

這種解決方案與 Egor 的遞歸算法基本相同,但沒有遞歸調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM