Looping in a spiral

前端 未结 30 2416
独厮守ぢ
独厮守ぢ 2020-11-22 15:07

A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fe

相关标签:
30条回答
  • 2020-11-22 15:19

    This is based on your own solution, but we can be smarter about finding the corners. This makes it easier to see how you might skip over the areas outside if M and N are very different.

    def spiral(X, Y):
        x = y = 0
        dx = 0
        dy = -1
        s=0
        ds=2
        for i in range(max(X, Y)**2):
                if abs(x) <= X and abs(y) <= Y/2:
                        print (x, y)
                        # DO STUFF...
                if i==s:
                        dx, dy = -dy, dx
                        s, ds = s+ds/2, ds+1
                x, y = x+dx, y+dy
    

    and a generator based solution that is better than O(max(n,m)^2), It is O(nm+abs(n-m)^2) because it skips whole strips if they are not part of the solution.

    def spiral(X,Y):
    X = X+1>>1
    Y = Y+1>>1
    x = y = 0
    d = side = 1
    while x<X or y<Y:
        if abs(y)<Y:
            for x in range(x, x+side, d):
                if abs(x)<X: yield x,y
            x += d
        else:
            x += side
        if abs(x)<X:
            for y in range(y, y+side, d):
                if abs(y)<Y: yield x,y
            y += d
        else:
            y += side
        d =-d
        side = d-side
    
    0 讨论(0)
  • 2020-11-22 15:19
    Here is my attempt for simple C solution. First print the outer spiral and move one block inside..and repeat.
    
    #define ROWS        5
    #define COLS        5
    //int A[ROWS][COLS] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {11, 12, 13, 14}, {15, 16, 17, 18} };
    //int A[ROWS][COLS] = { {1, 2, 3}, {6, 7, 8}, { 12, 13, 14} };
    //int A[ROWS][COLS] = { {1, 2}, {3, 4}};
    
    int A[ROWS][COLS] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15} , {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} };
    
    
    void print_spiral(int rows, int cols)
    {
        int row = 0;
        int offset = 0;
    
        while (offset < (ROWS - 1)) {
            /* print one outer loop at a time. */
            for (int col = offset; col <= cols; col++) {
                printf("%d ", A[offset][col]);
            }
    
            for (row = offset + 1; row <= rows; row++) {
                printf("%d ", A[row][cols]);
            }
    
            for (int col = cols - 1; col >= offset; col--) {
                printf("%d ", A[rows][col]);
            }
    
            for (row = rows - 1; row >= offset + 1; row--) {
                printf("%d ", A[row][offset]);
            }
    
           /* Move one block inside */
            offset++;
            rows--;
            cols--;
        }
        printf("\n");
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        print_spiral(ROWS-1, COLS-1);
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 15:21

    This is in C.

    I happened to choose bad variable names. In the names T == top, L == left, B == bottom, R == right. So, tli is top left i and brj is bottom right j.

    #include<stdio.h>
    
    typedef enum {
       TLTOR = 0,
       RTTOB,
       BRTOL,
       LBTOT
    } Direction;
    
    int main() {
       int arr[][3] = {{1,2,3},{4,5,6}, {7,8,9}, {10,11,12}};
       int tli = 0, tlj = 0, bri = 3, brj = 2;
       int i;
       Direction d = TLTOR;
    
       while (tli < bri || tlj < brj) {
         switch (d) {
         case TLTOR:
        for (i = tlj; i <= brj; i++) {
           printf("%d ", arr[tli][i]);
        }
        tli ++;
        d = RTTOB;
        break;
         case RTTOB:
        for (i = tli; i <= bri; i++) {
           printf("%d ", arr[i][brj]);
        }
        brj --;
        d = BRTOL;
        break;
         case BRTOL:
        for (i = brj; i >= tlj; i--) {
           printf("%d ", arr[bri][i]);
        }
        bri --;
            d = LBTOT;
        break;
         case LBTOT:
        for (i = bri; i >= tli; i--) {
           printf("%d ", arr[i][tlj]);
        }
        tlj ++;
            d = TLTOR;
        break;
     }
       }
       if (tli == bri == tlj == brj) {
          printf("%d\n", arr[tli][tlj]);
       }
    }
    
    0 讨论(0)
  • 2020-11-22 15:23

    TDD, in Java.

    SpiralTest.java:

    import java.awt.Point;
    import java.util.List;
    
    import junit.framework.TestCase;
    
    public class SpiralTest extends TestCase {
    
        public void test3x3() throws Exception {
            assertEquals("(0, 0) (1, 0) (1, 1) (0, 1) (-1, 1) (-1, 0) (-1, -1) (0, -1) (1, -1)", strung(new Spiral(3, 3).spiral()));
        }
    
        public void test5x3() throws Exception {
            assertEquals("(0, 0) (1, 0) (1, 1) (0, 1) (-1, 1) (-1, 0) (-1, -1) (0, -1) (1, -1) (2, -1) (2, 0) (2, 1) (-2, 1) (-2, 0) (-2, -1)",
                    strung(new Spiral(5, 3).spiral()));
        }
    
        private String strung(List<Point> points) {
            StringBuffer sb = new StringBuffer();
            for (Point point : points)
                sb.append(strung(point));
            return sb.toString().trim();
        }
    
        private String strung(Point point) {
            return String.format("(%s, %s) ", point.x, point.y);
        }
    
    }
    

    Spiral.java:

    import java.awt.Point;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Spiral {
        private enum Direction {
        E(1, 0) {Direction next() {return N;}},
        N(0, 1) {Direction next() {return W;}},
        W(-1, 0) {Direction next() {return S;}},
        S(0, -1) {Direction next() {return E;}},;
    
            private int dx;
            private int dy;
    
            Point advance(Point point) {
                return new Point(point.x + dx, point.y + dy);
            }
    
            abstract Direction next();
    
            Direction(int dx, int dy) {
                this.dx = dx;
                this.dy = dy;
            }
        };
        private final static Point ORIGIN = new Point(0, 0);
        private final int   width;
        private final int   height;
        private Point       point;
        private Direction   direction   = Direction.E;
        private List<Point> list = new ArrayList<Point>();
    
        public Spiral(int width, int height) {
            this.width = width;
            this.height = height;
        }
    
        public List<Point> spiral() {
            point = ORIGIN;
            int steps = 1;
            while (list.size() < width * height) {
                advance(steps);
                advance(steps);
                steps++;
            }
            return list;
        }
    
        private void advance(int n) {
            for (int i = 0; i < n; ++i) {
                if (inBounds(point))
                    list.add(point);
                point = direction.advance(point);
            }
            direction = direction.next();
        }
    
        private boolean inBounds(Point p) {
            return between(-width / 2, width / 2, p.x) && between(-height / 2, height / 2, p.y);
        }
    
        private static boolean between(int low, int high, int n) {
            return low <= n && n <= high;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:23

    Here is my solution (In Ruby)

    def spiral(xDim, yDim)
       sx = xDim / 2
       sy = yDim / 2
    
       cx = cy = 0
       direction = distance = 1
    
       yield(cx,cy)
       while(cx.abs <= sx || cy.abs <= sy)
          distance.times { cx += direction; yield(cx,cy) if(cx.abs <= sx && cy.abs <= sy); } 
          distance.times { cy += direction; yield(cx,cy) if(cx.abs <= sx && cy.abs <= sy); } 
          distance += 1
          direction *= -1
       end
    end
    
    spiral(5,3) { |x,y|
       print "(#{x},#{y}),"
    }
    
    0 讨论(0)
  • 2020-11-22 15:25

    Here's a C++ solution that shows that you can calculate the next (x, y) coordinates directly and easily from the previous ones - no need for tracking the current direction, radius, or anything else:

    void spiral(const int M, const int N)
    {
        // Generate an Ulam spiral centered at (0, 0).
        int x = 0;
        int y = 0;
    
        int end = max(N, M) * max(N, M);
        for(int i = 0; i < end; ++i)
        {
            // Translate coordinates and mask them out.
            int xp = x + N / 2;
            int yp = y + M / 2;
            if(xp >= 0 && xp < N && yp >= 0 && yp < M)
                cout << xp << '\t' << yp << '\n';
    
            // No need to track (dx, dy) as the other examples do:
            if(abs(x) <= abs(y) && (x != y || x >= 0))
                x += ((y >= 0) ? 1 : -1);
            else
                y += ((x >= 0) ? -1 : 1);
        }
    }
    

    If all you're trying to do is generate the first N points in the spiral (without the original problem's constraint of masking to an N x M region), the code becomes very simple:

    void spiral(const int N)
    {
        int x = 0;
        int y = 0;
        for(int i = 0; i < N; ++i)
        {
            cout << x << '\t' << y << '\n';
            if(abs(x) <= abs(y) && (x != y || x >= 0))
                x += ((y >= 0) ? 1 : -1);
            else
                y += ((x >= 0) ? -1 : 1);
        }
    }
    

    The trick is that you can compare x and y to determine what side of the square you're on, and that tells you what direction to move in.

    0 讨论(0)
提交回复
热议问题