algorithm - Printing 2d array in counterclockwise order -
how print array in counterclockwise order? know of famous "print array in spiral order" algorithm, it'd interesting see how print in counterclockwise fashion
assuming think of array of 2d coordinates ...
basically have sort array atn of quotient of y , x coordinates , print them in order. catering poles , sign changes while avoiding expensive , numerically unstable arithmetics complicates implementation. following pseudocode manly serves illustratin of principle.
the point set partitioned 9 categories numbered 0 8. #0 contains points (0,0) printed first, #1,3,5,7 contain points on positive y axis, negative x axis, negative y axis, , positive x axis, respectively. within each of these categories, points printed in order of increasing distance origin. categories #2,4,6,8 contain points second, third, fourth, , first quadrant, respectively. within each of these categories, points printed counterclockwise. points located on same vector origin printed in order of increasing distance origin.
let a:array of point(x:number,y:number) array. define f:array of (f1:number, f2:number, f3:number) componentwise as
f[i].f1 := let x := a[i].x, y := a[i].y; if x=0 if y=0 0 else if y>0 1 else 5 endif else if y=0 if x>0 7 else 3 else if x>0 , y>0 8 elsif x>0 , y<0 6 elsif x<0 , y<0 4 else 2 endif endif endif; f[i].f2 := let x := a[i].x, y := a[i].y, h := f[i].f1; if odd(h) abs(x) + abs(y) else if h=0 0 elsif h=2 -x/y elsif h=4 y/x elsif h=6 -x/y else y/x endif endif; f[i].f3 := a[i].x * a[i].x + a[i].y * a[i].y; apply favorite sorting algorithm order a lexicographically ascending f.f1, f.f2, f.f3 , print result in order.
Comments
Post a Comment