juli (caladri) wrote in dailysrc,
juli
caladri
dailysrc

Low-quality zig-zagging through a 2-dimensional array in C.

/*
 * Zig-Zag through an array that is w columns and h rows.  Find the stepth item
 * in the series.
 */
int *
zigzag(int **a, int w, int h, int step)
{
    int i, j;
    i = 0;
    j = 0;
    if (step-- == 0)
        goto done;
    ++i;
    for (;;) {
        if (step-- == 0)
            break;
        while (j + 1 < h && i > 0) {
            --i;
            ++j;
            if (step-- == 0)
                goto done;
        }
        if (j + 1 == h) {
            ++i;
        } else {
            ++j;
        }
        if (step-- == 0)
            goto done;
        while (i + 1 < w && j > 0) {
            --j;
            ++i;
            if (step-- == 0)
                goto done;
        }
        if (i + 1 == w) {
            ++j;
        } else {
            ++i;
        }
    }
done:
    return &a[j][i];
}

Subscribe
  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments