Algorithm for iterating over an outward spiral on a discrete 2D grid from the origin

前端 未结 12 1730
独厮守ぢ
独厮守ぢ 2020-12-05 06:54

For example, here is the shape of intended spiral (and each step of the iteration)

          y
          |
          |
   16 15 14 13 12
   17  4  3  2 11
--         


        
12条回答
  •  孤街浪徒
    2020-12-05 07:30

    Here's the algorithm. It rotates clockwise, but could easily rotate anticlockwise, with a few alterations. I made it in just under an hour.

    // spiral_get_value(x,y);
    sx = argument0;
    sy = argument1;
    a = max(sqrt(sqr(sx)),sqrt(sqr(sy)));
    c = -b;
    d = (b*2)+1;
    us = (sy==c and sx !=c);
    rs = (sx==b and sy !=c);
    bs = (sy==b and sx !=b);
    ls = (sx==c and sy !=b);
    ra = rs*((b)*2);
    ba = bs*((b)*4);
    la = ls*((b)*6);
    ax = (us*sx)+(bs*-sx);
    ay = (rs*sy)+(ls*-sy);
    add = ra+ba+la+ax+ay;
    value = add+sqr(d-2)+b;
    return(value);`
    

    It will handle any x / y values (infinite).

    It's written in GML (Game Maker Language), but the actual logic is sound in any programming language.

    The single line algorithm only has 2 variables (sx and sy) for the x and y inputs. I basically expanded brackets, a lot. It makes it easier for you to paste it into notepad and change 'sx' for your x argument / variable name and 'sy' to your y argument / variable name.

    `// spiral_get_value(x,y);
    
    sx = argument0;  
    sy = argument1;
    
    value = ((((sx==max(sqrt(sqr(sx)),sqrt(sqr(sy))) and sy !=(-1*max(sqrt(sqr(sx)),sqrt(sqr(sy))))))*((max(sqrt(sqr(sx)),sqrt(sqr(sy))))*2))+(((sy==max(sqrt(sqr(sx)),sqrt(sqr(sy))) and sx !=max(sqrt(sqr(sx)),sqrt(sqr(sy)))))*((max(sqrt(sqr(sx)),sqrt(sqr(sy))))*4))+(((sx==(-1*max(sqrt(sqr(sx)),sqrt(sqr(sy)))) and sy !=max(sqrt(sqr(sx)),sqrt(sqr(sy)))))*((max(sqrt(sqr(sx)),sqrt(sqr(sy))))*6))+((((sy==(-1*max(sqrt(sqr(sx)),sqrt(sqr(sy)))) and sx !=(-1*max(sqrt(sqr(sx)),sqrt(sqr(sy))))))*sx)+(((sy==max(sqrt(sqr(sx)),sqrt(sqr(sy))) and sx !=max(sqrt(sqr(sx)),sqrt(sqr(sy)))))*-sx))+(((sx==max(sqrt(sqr(sx)),sqrt(sqr(sy))) and sy !=(-1*max(sqrt(sqr(sx)),sqrt(sqr(sy))))))*sy)+(((sx==(-1*max(sqrt(sqr(sx)),sqrt(sqr(sy)))) and sy !=max(sqrt(sqr(sx)),sqrt(sqr(sy)))))*-sy))+sqr(((max(sqrt(sqr(sx)),sqrt(sqr(sy)))*2)+1)-2)+max(sqrt(sqr(sx)),sqrt(sqr(sy)));
    
    return(value);`
    

    I know the reply is awfully late :D but i hope it helps future visitors.

提交回复
热议问题