Rep-string: Difference between revisions
Content added Content deleted
No edit summary |
(→{{header|Haskell}}: Delegated output formatting of 2nd version to a generic fTable function. Updated output.) |
||
Line 1,109: | Line 1,109: | ||
Or, alternatively: |
Or, alternatively: |
||
<lang haskell>import Data.List (inits, intercalate, transpose) |
<lang haskell>import Data.List (inits, intercalate, transpose) |
||
import Control.Applicative (liftA2) |
|||
import Data.Bool (bool) |
|||
-- REP-CYCLES |
-- REP-CYCLES --------------------------------------------- |
||
repCycles :: String -> [String] |
repCycles :: String -> [String] |
||
repCycles cs = |
repCycles cs = |
||
Line 1,116: | Line 1,118: | ||
in filter ((cs ==) . take n . cycle) (tail $ inits (take (quot n 2) cs)) |
in filter ((cs ==) . take n . cycle) (tail $ inits (take (quot n 2) cs)) |
||
⚫ | |||
cycleReport :: String -> [String] |
|||
cycleReport xs = |
|||
⚫ | |||
in [ xs |
|||
, if not (null reps) |
|||
then last reps |
|||
else "(n/a)" |
|||
] |
|||
⚫ | |||
main :: IO () |
main :: IO () |
||
main = |
main = |
||
putStrLn "Longest cycles:\n" |
|||
putStrLn $ |
putStrLn $ |
||
fTable |
|||
⚫ | |||
"Longest cycles:\n" |
|||
id |
|||
((flip bool "n/a" . last) <*> null) |
|||
⚫ | |||
[ "1001110011" |
[ "1001110011" |
||
, "1110111011" |
, "1110111011" |
||
Line 1,146: | Line 1,140: | ||
] |
] |
||
-- GENERIC |
-- GENERIC ------------------------------------------------ |
||
fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String |
|||
fTable s xShow fxShow f xs = |
|||
table delim rows = |
|||
let w = maximum (length . xShow <$> xs) |
|||
intercalate delim <$> |
|||
rjust n c = liftA2 drop length (replicate n c ++) |
|||
transpose |
|||
⚫ | |||
((\col -> |
|||
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</lang> |
|||
let width = (length $ maximum col) |
|||
justifyLeft n c s = take n (s ++ replicate n c) |
|||
in justifyLeft width ' ' <$> col) <$> |
|||
transpose rows)</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>Longest cycles: |
<pre>Longest cycles: |
||
1001110011 |
1001110011 -> 10011 |
||
1110111011 |
1110111011 -> 1110 |
||
0010010010 |
0010010010 -> 001 |
||
1010101010 |
1010101010 -> 1010 |
||
1111111111 |
1111111111 -> 11111 |
||
0100101101 |
0100101101 -> n/a |
||
0100100 -> 010 |
|||
101 -> n/a |
|||
11 -> 1 |
|||
00 -> 0 |
|||
1 -> n/a</pre> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |