0

如何以逆时针顺序打印数组?我知道著名的“以螺旋顺序打印数组”算法,但看看如何以逆时针方式打印它会很有趣

4

1 回答 1

0

假设您想到一个二维坐标数组......

基本上,您必须按 y 和 x 坐标的商的 atn 对数组进行排序,然后按顺序打印它们。适当地满足极点和符号变化,同时避免昂贵和数值不稳定的算术使实现复杂化。以下伪代码主要用于说明原理。

点集分为 0 到 8 的 9 个类别。#0 包含(0,0)将首先打印的点,#1,3,5,7 包含正 y 轴、负 x 轴、负 y 轴和正 x 上的点轴,分别。在这些类别中的每一个中,点将按照与原点的距离增加的顺序打印。类别 #2,4,6,8 分别包含来自第二、第三、第四和第一象限的点。在每个类别中,点将逆时针打印。位于与原点相同矢量上的任何点都将按照与原点的距离增加的顺序打印。

a:array of point(x:number,y:number)成为你的阵列。将f:array of (f1:number, f2:number, f3:number)组件定义为

f[i].f1 :=
    let x := a[i].x, y := a[i].y;
    if x=0 then
        if y=0 then
            0
        else
            if y>0 then 1 else 5
        endif
    else
        if y=0 then
            if x>0 then 7 else 3
        else
            if x>0 and y>0 then
                8
            elsif x>0 and y<0 then
                6
            elsif x<0 and y<0 then
                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) then
        abs(x) + abs(y)
    else
        if h=0 then
            0
        elsif h=2 then
            -x/y
        elsif h=4 then
            y/x
        elsif h=6 then
            -x/y
        else
            y/x
        endif
    endif;

f[i].f3 :=
    a[i].x * a[i].x + a[i].y * a[i].y;

应用您最喜欢的排序算法按a字典顺序升序排序并按顺序f.f1, f.f2, f.f3打印结果。

于 2013-03-06T01:46:37.053 回答