Floyd's triangle: Difference between revisions
Content added Content deleted
(→{{header|Haskell}}: Added a variant defining the triangle in terms of Data.Matrix) |
|||
Line 3,163: | Line 3,163: | ||
[79,80,81,82,83,84,85,86,87,88,89,90,91] |
[79,80,81,82,83,84,85,86,87,88,89,90,91] |
||
[92,93,94,95,96,97,98,99,100,101,102,103,104,105]</pre> |
[92,93,94,95,96,97,98,99,100,101,102,103,104,105]</pre> |
||
Or as a partially populated matrix: |
|||
<lang haskell>import Control.Monad (join) |
|||
import Data.Matrix (Matrix, getElem, matrix, nrows, toLists) |
|||
--------------------- FLOYDS TRIANGLE -------------------- |
|||
floyd :: Int -> Matrix (Maybe Int) |
|||
floyd n = matrix n n go |
|||
where |
|||
go (y, x) |
|||
| x > y = Nothing |
|||
| otherwise = Just (x + quot (pred y * y) 2) |
|||
--------------------------- TEST ------------------------- |
|||
main :: IO () |
|||
main = mapM_ putStrLn $ showFloyd . floyd <$> [5, 14] |
|||
------------------------- DISPLAY ------------------------ |
|||
showFloyd :: Matrix (Maybe Int) -> String |
|||
showFloyd m = |
|||
(unlines . fmap unwords . toLists) $ |
|||
go <$> m |
|||
where |
|||
go Nothing = "" |
|||
go (Just n) = padRight w (show n) |
|||
Just v = join getElem (nrows m) m |
|||
w = length (show v) |
|||
padRight :: Int -> String -> String |
|||
padRight n = (drop . length) <*> (replicate n ' ' <>)</lang> |
|||
{{Out}} |
|||
<pre> 1 |
|||
2 3 |
|||
4 5 6 |
|||
7 8 9 10 |
|||
11 12 13 14 15 |
|||
1 |
|||
2 3 |
|||
4 5 6 |
|||
7 8 9 10 |
|||
11 12 13 14 15 |
|||
16 17 18 19 20 21 |
|||
22 23 24 25 26 27 28 |
|||
29 30 31 32 33 34 35 36 |
|||
37 38 39 40 41 42 43 44 45 |
|||
46 47 48 49 50 51 52 53 54 55 |
|||
56 57 58 59 60 61 62 63 64 65 66 |
|||
67 68 69 70 71 72 73 74 75 76 77 78 |
|||
79 80 81 82 83 84 85 86 87 88 89 90 91 |
|||
92 93 94 95 96 97 98 99 100 101 102 103 104 105</pre> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |