Spiral matrix: Difference between revisions
Content added Content deleted
m (→{{header|Factor}}: grade, not rank!) |
(→Functional Solutions: Added a pure functional variant (without generative mutation)) |
||
Line 3,858: | Line 3,858: | ||
print ' '.join('%3s' % x for x in row)</lang> |
print ' '.join('%3s' % x for x in row)</lang> |
||
===Functional |
===Functional Solutions=== |
||
{{works with|Python|2.6, 3.0}} |
{{works with|Python|2.6, 3.0}} |
||
<lang python>import itertools |
<lang python>import itertools |
||
Line 3,879: | Line 3,879: | ||
for row in spiral(5): |
for row in spiral(5): |
||
print(' '.join('%3s' % x for x in row))</lang> |
print(' '.join('%3s' % x for x in row))</lang> |
||
Or, as an alternative to generative mutation: |
|||
{{Works with|Python|3.7}} |
|||
{{Trans|Haskell}} |
|||
<lang python>'''Spiral Matrix''' |
|||
# spiral :: Int -> [[Int]] |
|||
def spiral(n): |
|||
'''The rows of a spiral matrix of order N. |
|||
''' |
|||
def go(rows, cols, x): |
|||
return [list(range(x, x + cols))] + [ |
|||
list(reversed(x)) for x |
|||
in zip(*go(cols, rows - 1, x + cols)) |
|||
] if 0 < rows else [[]] |
|||
return go(n, n, 0) |
|||
# TEST ---------------------------------------------------- |
|||
# main :: IO () |
|||
def main(): |
|||
'''Spiral matrix of order 5, in wiki table markup''' |
|||
print(wikiTable( |
|||
spiral(5) |
|||
)) |
|||
# FORMATTING ---------------------------------------------- |
|||
# wikiTable :: [[a]] -> String |
|||
def wikiTable(rows): |
|||
'''Wiki markup for a no-frills tabulation of rows.''' |
|||
return '{| class="wikitable" style="' + ( |
|||
'width:12em;height:12em;table-layout:fixed;"|-\n' |
|||
) + '\n|-\n'.join([ |
|||
'| ' + ' || '.join([str(cell) for cell in row]) |
|||
for row in rows |
|||
]) + '\n|}' |
|||
# MAIN --- |
|||
if __name__ == '__main__': |
|||
main()</lang> |
|||
{| class="wikitable" style="width:12em;height:12em;table-layout:fixed;"|- |
|||
| 0 || 1 || 2 || 3 || 4 |
|||
|- |
|||
| 15 || 16 || 17 || 18 || 5 |
|||
|- |
|||
| 14 || 23 || 24 || 19 || 6 |
|||
|- |
|||
| 13 || 22 || 21 || 20 || 7 |
|||
|- |
|||
| 12 || 11 || 10 || 9 || 8 |
|||
|} |
|||
=== Simple solution === |
=== Simple solution === |