Skip to content

Instantly share code, notes, and snippets.

@guilt
Last active December 13, 2023 14:04
Show Gist options
  • Save guilt/c421db704a84a1b79e423d96bd11bb0b to your computer and use it in GitHub Desktop.
Save guilt/c421db704a84a1b79e423d96bd11bb0b to your computer and use it in GitHub Desktop.
ZigZag Iterator
# pylint: disable=invalid-name
# pylint: disable=unused-argument
"ZigZag iterator."
import sys
if sys.version_info[0] >= 3:
xrange = range
def move(x, y, columns, rows):
"Tells us what to do next with x and y."
if y < (rows - 1):
return max(0, x-1), y+1
return x+1, y
def zigzag(rows, columns):
"ZigZag iterator, yields indices."
x, y = 0, 0
size = rows * columns
for _ in xrange(size):
yield y, x
if (x + y) & 1:
x, y = move(x, y, columns, rows)
else:
y, x = move(y, x, rows, columns)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment