Diagonal snake filling array

  • A+
Category:Languages

Python 3.7. I'm trying to fill multidimensional array (n*m size) in diagonal-snake pattern:

1   3   4   10  11  21 2   5   9   12  20  22 6   8   13  19  23  30 7   14  18  24  29  31 15  17  25  28  32  35 16  26  27  33  34  36 

I have a function for n x n size and it works fine for it. But for n x m size it returns:

1 3  4  10 14  2 5  9  15 20  6 8  16 19 19  7 17 18 20 21 

My code:

def method1(i, j, n, m):     num = i+j     summ = num * (num + 1) >> 1     s = n * m     if num > n-1:         t = 2*(n-1) - (i+j) + 1         s -= t*(t+1) >> 1      if num & 1:         if num > n-1:             return s + (n-i)         else:             return summ + j+1     if num > n-1:         return s + (n-j)     else:         return summ + i+1  for i in range(n):     for j in range(m):         print(method1(i, j, n, m), end=" ")     print('/n') 

What am I doing wrong? P.S. Your answer can be in any language.

 


not clear what you are doing wrong, but the following code should work:

import numpy as np  n = 4 m = 5  x, y = (0, 0) ux, uy = (1, -1)  a = np.zeros((n, m)) for i in range(n*m):   print((x, y), i+1)   a[x, y] = i + 1   x, y = (x + ux, y + uy)   if y == m:     print('right side')  # including corner     y = m - 1     x += 2   elif x == n:     print('bottom side')  # including corner     x = n - 1     y += 2   elif x == -1:     print('top side')     x = 0   elif y == -1:     print('left side')     y = 0   else:     continue   ux, uy = -ux, -uy print(a) 

output:

(0, 0) 1 left side (1, 0) 2 (0, 1) 3 top side (0, 2) 4 (1, 1) 5 (2, 0) 6 left side (3, 0) 7 (2, 1) 8 (1, 2) 9 (0, 3) 10 top side (0, 4) 11 (1, 3) 12 (2, 2) 13 (3, 1) 14 bottom side (3, 2) 15 (2, 3) 16 (1, 4) 17 right side (2, 4) 18 (3, 3) 19 bottom side (3, 4) 20 right side [[ 1.  3.  4. 10. 11.]  [ 2.  5.  9. 12. 17.]  [ 6.  8. 13. 16. 18.]  [ 7. 14. 15. 19. 20.]] 

To write this, it helped a lot to draw a diagram.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: