Created
July 27, 2012 03:17
-
-
Save flazz/3185997 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Sux where | |
import Data.List | |
sux :: Ord a => [a] -> Maybe [a] | |
sux ns = sux' ns [] | |
sux' :: Ord a => [a] -> [a] -> Maybe [a] | |
sux' pfx sfx | |
| canInc sfx = Just $ pfx ++ (inc sfx) | |
| null pfx = Nothing | |
| otherwise = sux' pfx' sfx' | |
where (pfx', sfx') = pfx << sfx | |
inc :: Ord a => [a] -> [a] | |
inc (n:ns) = m : rest | |
where (highers, lowers) = partition (> n) ns | |
m:ms = sort highers | |
rest = sort $ ms ++ [n] ++ lowers | |
canInc :: Ord a => [a] -> Bool | |
canInc = not . descending | |
where descending ns = reverse ns == sort ns | |
(<<) :: [a] -> [a] -> ([a], [a]) | |
as << bs = (as', bs') | |
where as' = init as | |
bs' = (last as):bs |
goodfoo
commented
Jul 27, 2012
class Succ
def succ(n)
ar = n_to_array(n)
bag = [ar.pop]
succ1(ar, bag).join.to_i
end
private
def succ1(head, bag)
return bag if head.empty?
x = head.pop
min = bag.select { |n| n > x } . min
if min
head << bag.delete(min)
bag << x
return head + bag.sort
end
bag.unshift x
succ1(head,bag)
end
def n_to_array(n)
s = n.to_s
ar = s.chars.map { |c| c.to_i }
ar
end
end
s = Succ.new
p s.succ(13452)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment