algoritmo: buscando un método más eficiente para describir un rectángulo cuadriculado para que un robot pueda tocar cada punto d

CorePress2024-01-24  14

He estado intentando codificar una solución para que un robot toque cada punto de una cuadrícula cuadrada o rectangular.

Hasta ahora he estado trabajando en una solución en espiral que comienza en la parte inferior izquierda y gira en espiral hacia el centro y la he conseguido funcionar y parece funcionar en cuadrículas pares (cuadradas) o desiguales (rectangulares).

Me preguntaba si hay una solución más eficiente o elegante en cuanto a código que la que tengo a continuación.

Soy bastante nuevo en la codificación y me encantaría recibir comentarios sobre cómo se podría mejorar este código o si me falta una solución matemática más simple, etc.

Por ejemplo: una cuadrícula de 5 x 5 y [S] es la posición inicial en espiral hacia la posición 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]

por el momento mi código se ve así y funciona bien. No es necesario que sea una espiral, así es como se forma la c.La oda actualmente funciona.

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

Cualquier ayuda o crítica constructiva será muy apreciada.



------------------------------------

Si quieres tocar cada punto de la cuadrícula, no hay nada más eficiente que moverte de un punto a otro, tocando cada punto solo una vez. Eso es lo que estás haciendo.

Puedes hacerlo en espiral, en filas, en columnas o una combinación de ambas. No importa ya que el número de movimientos es siempre el mismo.

La única diferencia es dónde está el punto final.

1

Perdón si formulé mal mi pregunta. cuando dije eficiente quise decir desde un punto de programación o algorítmico. Entiendo que mi código va de un punto a otro, pero ¿necesitamos todos esos bucles? A veces veo soluciones a otros problemas que son tan compactas y eficientes en cuanto a código y me preguntaba si lo mismo ocurría aquí, ya que mi código se siente inflado. también gracias por tu respuesta

- Dirge0matic

27/03/2021 a las 19:22



------------------------------------

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

Esta solución es básicamente la misma que el algoritmo recursivo de Egor, pero sin una llamada recursiva.

Su guía para un futuro mejor - libreflare
Su guía para un futuro mejor - libreflare