如何记录移动方向是SAS?

时间:2016-12-17 14:25:21

标签: macros sas sas-macro

我有一个像这样的迷宫文件。

1111111
1001111
1101101
1101001
1100011
1111111

格式$ direction指示方向

start end label
D     D    down
L     L    left
R     R    right
U     U    up

然后,我有一个指示起点和终点的数据集。

Row   Column
start  2      2
end    3      6

如何记录从开始到结束的移动方向?

direction  row column
           2    2
right      2    3
down       3    3      
down       4    3
down       5    3

我使用数组

array m(i,j)
if  m(i,j) = 0 then
row=i;
column=j;
output;

然而,它只是没有按照正确的移动顺序。

谢谢,如果你能提供帮助。

1 个答案:

答案 0 :(得分:1)

这是实现这一目标的一种方式。使用SAS数据步骤逻辑编写更通用的迷宫求解算法留给读者练习,但这应该适用于迷宫。

/* Define the format */

proc format;
 value $direction
 'D' = 'down'
 'L' = 'left'
 'R' = 'right'
 'U' = 'up'
;
run;


data want;

/*Read in the maze and start/end points in (y,x) orientation*/
array maze(6,7) (
1,1,1,1,1,1,1,
1,0,0,1,1,1,1,
1,1,0,1,1,0,1,
1,1,0,1,0,0,1,
1,1,0,0,0,1,1,
1,1,1,1,1,1,1
);
array endpoints (2,2) (
2,2
3,6
);
/*Load the start point and output a row*/
x = endpoints(1,2);
y = endpoints(1,1);
output;

/*
 Navigate through the maze.
 Assume for the sake of simplicity that it is really more of a labyrinth,
 i.e. there is only ever one valid direction in which to move, 
 other than the direction you just came from,
 and that the end point is reachable
*/
do _n_ = 1 by 1 until(x = endpoints(2,2) and y = endpoints(2,1));
    if maze(y-1,x) = 0 and direction ne 'D' then do;
        direction = 'U';
        y + -1;
    end;
    else if maze(y+1,x) = 0 and direction ne 'U' then do;
        direction = 'D';
        y + 1;
    end;
    else if maze(y,x-1) = 0 and direction ne 'R' then do;
        direction = 'L';
        x + -1;
    end;    
    else if maze(y,x+1) = 0 and direction ne 'L' then do;
        direction = 'R';
        x + 1;
    end;            
    output;
    if _n_ > 15 then stop; /*Set a step limit in case something goes wrong*/
end;
format direction $direction.;
drop maze: endpoints:;
run;