Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.forth > #50870

Rosetta Code: Zig-zag matrix

From "WJ" <w_a_x_man@yahoo.com>
Newsgroups comp.lang.forth
Subject Rosetta Code: Zig-zag matrix
Date 2016-09-12 02:52 +0000
Organization A noiseless patient Spider
Message-ID <nr558f$3l8$1@dont-email.me> (permalink)

Show all headers | View raw


> A  zig-zag  array is a square arrangement of the first  N^2
> integers, 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: 
> 
>  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


Ruby:

def out(n, limit)
  not (0 ... limit).include?(n)
end

n = 12
board = Array.new(n){Array.new(n,0)}
x=y=0 ; delta = 1
1.upto(n*n-1){|i|
  newx = x + delta; newy = y - delta
  if out(newy,n)
    newy = y
    newx = x + 1
  end
  if out(newx,n)
    newx = x
    newy = y + 1
  end
  delta = -delta if x==newx or y==newy
  board[y=newy][x=newx] = i
}

def show board
  w = (board.last.last).to_s.size
  puts board.map{|row| row.map{|n| n.to_s.rjust(w)}.join " "}
end

show board

  0   1   5   6  14  15  27  28  44  45  65  66
  2   4   7  13  16  26  29  43  46  64  67  88
  3   8  12  17  25  30  42  47  63  68  87  89
  9  11  18  24  31  41  48  62  69  86  90 107
 10  19  23  32  40  49  61  70  85  91 106 108
 20  22  33  39  50  60  71  84  92 105 109 122
 21  34  38  51  59  72  83  93 104 110 121 123
 35  37  52  58  73  82  94 103 111 120 124 133
 36  53  57  74  81  95 102 112 119 125 132 134
 54  56  75  80  96 101 113 118 126 131 135 140
 55  76  79  97 100 114 117 127 130 136 139 141
 77  78  98  99 115 116 128 129 137 138 142 143

In Forth?


-- 
[A]n unholy alliance of leftists, capitalists, and Zionist supremacists has
schemed to promote immigration and miscegenation with the deliberate aim of
breeding us out of existence in our own homelands....  [T]he real aim stays the
same: the biggest genocide in human history....  --- Nick Griffin
(https://www.youtube.com/watch?v=K0hD7IffTJs)

Back to comp.lang.forth | Previous | Next — Next in thread | Find similar | Unroll thread


Thread

Rosetta Code: Zig-zag matrix "WJ" <w_a_x_man@yahoo.com> - 2016-09-12 02:52 +0000
  Re: Rosetta Code: Zig-zag matrix Paul Rubin <no.email@nospam.invalid> - 2016-09-11 22:05 -0700
    Re: Rosetta Code: Zig-zag matrix albert@cherry.spenarnc.xs4all.nl (Albert van der Horst) - 2016-09-12 13:50 +0200
      Re: Rosetta Code: Zig-zag matrix Paul Rubin <no.email@nospam.invalid> - 2016-09-12 13:12 -0700
        Re: Rosetta Code: Zig-zag matrix albert@cherry.spenarnc.xs4all.nl (Albert van der Horst) - 2016-09-12 22:38 +0200
          Re: Rosetta Code: Zig-zag matrix Paul Rubin <no.email@nospam.invalid> - 2016-09-12 14:15 -0700

csiph-web