segmento.m 1023 Bytes
Newer Older
Giuseppe Lombardi's avatar
Giuseppe Lombardi committed
1 2 3
%Dato in input (x,y) calcola la distanza cavallo
%La function segue un approccio greedy

Giuseppe Lombardi's avatar
Giuseppe Lombardi committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
function S=segmento(x, y)
if x<0
	x=-x;
endif
if y<0
	y=-y;
endif
S(:,1)=[x, y];
r1=x;
r2=y;
k=2;
while r1 != 0 || r2 != 0
	if [r1, r2] == [2, 2]
		S(:,k)=[1;0];
		S(:,k+1)=[0;2];
		S(:,k+2)=[-2;1];
		S(:,k+3)=[0;0];
		r1=0;
		r2=0;
	endif
	if [r1, r2] == [1, 0] || [r1, r2] == [0, 1]
		S(:,k)=[-1;-1];
		S(:,k+1)=[-2;1];
		S(:,k+2)=[0;0];
		r1=0;
		r2=0;		
	endif
	if [r1, r2] == [0, 2]
		S(:,k)=[-2;1];
		S(:,k+1)=[0;0];
		r1=0;
		r2=0;		
	endif
	if [r1, r2] == [2, 0]
		S(:,k)=[1;-2];
		S(:,k+1)=[0;0];
		r1=0;
		r2=0;
	endif
	if [r1, r2] == [1, 1]
		S(:,k)=[2;-1];
		S(:,k+1)=[0;0];
		r1=0;
		r2=0;
	endif
	if r1 !=0 || r2 != 0 
		if r1 >= r2
			r1 = r1-2;
			r2 = r2-1;
		else
			r1 = r1-1;
			r2 = r2-2;
		endif
		S(:,k)=[r1; r2];
	endif
	if r1<0
		r1=-r1;
	endif
	if r2<0
		r2=-r2;
	endif
	k=k+1;
endwhile
x=S(1,:);
y=S(2,:);
k=size(S)(2)-1
%set grid xtics (-10,0.5,10);
%set grid ytics (-10,0.5,10);
plot(x,y,"o");
endfunction