Next highest int from digits: Difference between revisions

Content added Content deleted
m (→‎Haskell :: Minimal digit-swaps: (Restored cropped final line of output))
m (→‎Haskell Minimal digit-swaps: (slight pruning of splitBy))
Line 293: Line 293:


<lang haskell>import Data.List (unfoldr)
<lang haskell>import Data.List (unfoldr)

digitShuffleSuccessors
digitShuffleSuccessors
:: Integral b
:: Integral b
Line 306: Line 306:
else Just (ds, (go . reverse) ds))
else Just (ds, (go . reverse) ds))
(go (reversedDigits n))
(go (reversedDigits n))

minimalSwap
minimalSwap
:: Ord a
:: Ord a
Line 316: Line 316:
let (less, h:more) = break (> pivot) reversedSuffix
let (less, h:more) = break (> pivot) reversedSuffix
in reverse (h : prefix) ++ less ++ pivot : more
in reverse (h : prefix) ++ less ++ pivot : more

---------------------------TEST----------------------------
---------------------------TEST----------------------------
main :: IO ()
main :: IO ()
Line 333: Line 333:
digitShuffleSuccessors
digitShuffleSuccessors
[0, 9, 12, 21, 12453, 738440, 45072010, 95322020]
[0, 9, 12, 21, 12453, 738440, 45072010, 95322020]
putStrLn $
putStrLn $
fTable
fTable
Line 340: Line 341:
(take 10 . digitShuffleSuccessors)
(take 10 . digitShuffleSuccessors)
[9589776899767587796600]
[9589776899767587796600]

--------------------------GENERIC--------------------------
--------------------------GENERIC--------------------------
reversedDigits
reversedDigits
Line 350: Line 351:
go 0 = []
go 0 = []
go x = rem x 10 : go (quot x 10)
go x = rem x 10 : go (quot x 10)

splitBy :: (a -> a -> Bool) -> [a] -> ([a], [a])
splitBy :: (a -> a -> Bool) -> [a] -> ([a], [a])
splitBy f xs = go $ break (uncurry f) $ zip xs (tail xs)
splitBy f xs = go $ break (uncurry f) $ zip xs (tail xs)
Line 356: Line 357:
go (ys, zs)
go (ys, zs)
| null ys = ([], xs)
| null ys = ([], xs)
| null zs = (xs, [])
| otherwise = (fst (head ys) : map snd ys, map snd zs)
| otherwise = (fst (head ys) : map snd ys, map snd zs)

unDigits
unDigits
:: (Foldable t, Num a)
:: (Foldable t, Num a)
=> t a -> a
=> t a -> a
unDigits = foldl (\a b -> 10 * a + b) 0
unDigits = foldl (\a b -> 10 * a + b) 0

--------------------------DISPLAY--------------------------
--------------------------DISPLAY--------------------------
fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String
fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String
Line 371: Line 371:
where
where
w = maximum (length . xShow <$> xs)
w = maximum (length . xShow <$> xs)

rjust :: Int -> Char -> String -> String
rjust :: Int -> Char -> String -> String
rjust n c = drop . length <*> (replicate n c ++)</lang>
rjust n c = drop . length <*> (replicate n c ++)</lang>