How to resolve the algorithm Zig-zag matrix step by step in the Python programming language
How to resolve the algorithm Zig-zag matrix step by step in the Python programming language
Table of Contents
Problem Statement
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Zig-zag matrix step by step in the Python programming language
First Code (zigzag
and printzz
functions)
-
The
zigzag
function generates a dictionary representing a zigzag traversal order for a square matrix of a given sizen
.- It uses a custom
compare
function to sort the coordinates of the matrix cells in a zigzag pattern.
- It uses a custom
-
The
printzz
function takes the output of thezigzag
function and prints the matrix values in a zigzag pattern.
Second Code (move
, zigzag
functions)
-
The
move
function takes the current position (x, y) in a matrix and calculates the next position to visit in the zigzag pattern. -
The
zigzag
function generates a sequence of coordinates (y, x) representing a zigzag traversal order for a matrix of sizerows
xcolumns
. -
The test code fills a matrix with numbers in zigzag order using the
zigzag
function and prints it.
Third Code (CX
, COLS
constants)
-
The code defines a generator function
CX
that yields a sequence of x coordinates for a zigzag traversal of a matrix withCOLS
columns. -
It uses a list comprehension to create a list of nested generators, each representing a row in the zigzag traversal.
-
The code then iterates through the rows and columns to print the matrix values in a zigzag pattern.
Fourth Code (zigzag
function)
-
The
zigzag
function generates a list of zigzag indexes for a square array of a givendimension
. -
It uses a symmetrical property to generate only half of the indexes and then reverse the order for the other half.
-
The function returns a list of indexes representing the zigzag traversal order.
-
The
main
function tests thezigzag
function and prints the zigzag indexes for a given dimension.
Source code in the python programming language
def zigzag(n):
'''zigzag rows'''
def compare(xy):
x, y = xy
return (x + y, -y if (x + y) % 2 else y)
xs = range(n)
return {index: n for n, index in enumerate(sorted(
((x, y) for x in xs for y in xs),
key=compare
))}
def printzz(myarray):
'''show zigzag rows as lines'''
n = int(len(myarray) ** 0.5 + 0.5)
xs = range(n)
print('\n'.join(
[''.join("%3i" % myarray[(x, y)] for x in xs) for y in xs]
))
printzz(zigzag(6))
# 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)
# test code
i, rows, cols = 0, 5, 5
mat = [[0 for x in range(cols)] for y in range(rows)]
for (y, x) in zigzag(rows, cols):
mat[y][x], i = i, i + 1
from pprint import pprint
pprint(mat)
[[0, 1, 5, 6, 14],
[2, 4, 7, 13, 15],
[3, 8, 12, 16, 21],
[9, 11, 17, 20, 22],
[10, 18, 19, 23, 24]]
COLS = 9
def CX(x, ran):
while True:
x += 2 * next(ran)
yield x
x += 1
yield x
ran = []
d = -1
for V in CX(1,iter(list(range(0,COLS,2)) + list(range(COLS-1-COLS%2,0,-2)))):
ran.append(iter(range(V, V+COLS*d, d)))
d *= -1
for x in range(0,COLS):
for y in range(x, x+COLS):
print(repr(next(ran[y])).rjust(3), end = ' ')
print()
from __future__ import print_function
import math
def zigzag( dimension):
''' generate the zigzag indexes for a square array
Exploiting the fact that an array is symmetrical around its
centre
'''
NUMBER_INDEXES = dimension ** 2
HALFWAY = NUMBER_INDEXES // 2
KERNEL_ODD = dimension & 1
xy = [0 for _ in range(NUMBER_INDEXES)]
# start at 0,0
ix = 0
iy = 0
# 'fake' that we are going up and right
direction = 1
# the first index is always 0, so start with the second
# until halfway
for i in range(1, HALFWAY + KERNEL_ODD):
if direction > 0:
# going up and right
if iy == 0:
# are at top
ix += 1
direction = -1
else:
ix += 1
iy -= 1
else:
# going down and left
if ix == 0:
# are at left
iy += 1
direction = 1
else:
ix -= 1
iy += 1
# update the index position
xy[iy * dimension + ix] = i
# have first half, but they are scattered over the list
# so find the zeros to replace
for i in range(1, NUMBER_INDEXES):
if xy[i] == 0 :
xy[i] = NUMBER_INDEXES - 1 - xy[NUMBER_INDEXES - 1 - i]
return xy
def main(dim):
zz = zigzag(dim)
print( 'zigzag of {}:'.format(dim))
width = int(math.ceil(math.log10(dim**2)))
for j in range(dim):
for i in range(dim):
print('{:{width}}'.format(zz[j * dim + i], width=width), end=' ')
print()
if __name__ == '__main__':
main(5)
You may also check:How to resolve the algorithm Queue/Usage step by step in the REBOL programming language
You may also check:How to resolve the algorithm Haversine formula step by step in the BASIC programming language
You may also check:How to resolve the algorithm Window management step by step in the Tcl programming language
You may also check:How to resolve the algorithm Variables step by step in the Ruby programming language
You may also check:How to resolve the algorithm Generic swap step by step in the Haskell programming language