Rebol3 Code Examplex


Floyd's triangle

Rebol [
    title: "Rosetta code: Floyd's triangle"
    file:  %Floyd's_triangle.r3
    url:   https://rosettacode.org/wiki/Floyd%27s_triangle
]

print-floyd: function [
    "Prints Floyd's triangle with aligned columns"
    rows [integer!]
][
    c: 1
    h: rows * (rows - 1) >> 1          ;; starting number of the last row
    repeat i rows [
        s: clear ""
        repeat j i [
            width: length? form h + j  ;; column width based on last row's value
            if j > 1 [append s space]
            append s pad c negate width
            ++ c
        ]
        print [pad i -3 "|" s]
    ]
]

foreach rows [5 14][
    print [as-yellow "Floyd's triangle with rows:" rows]
    print-floyd rows
    print ""
]

Output:

Floyd's triangle with rows: 5
  1 |  1
  2 |  2  3
  3 |  4  5  6
  4 |  7  8  9 10
  5 | 11 12 13 14 15

Floyd's triangle with rows: 14
  1 |  1
  2 |  2  3
  3 |  4  5  6
  4 |  7  8  9 10
  5 | 11 12 13 14 15
  6 | 16 17 18 19 20 21
  7 | 22 23 24 25 26 27 28
  8 | 29 30 31 32 33 34 35 36
  9 | 37 38 39 40 41 42 43 44  45
 10 | 46 47 48 49 50 51 52 53  54  55
 11 | 56 57 58 59 60 61 62 63  64  65  66
 12 | 67 68 69 70 71 72 73 74  75  76  77  78
 13 | 79 80 81 82 83 84 85 86  87  88  89  90  91
 14 | 92 93 94 95 96 97 98 99 100 101 102 103 104 105