Next highest int from digits: Difference between revisions

m (→‎{{header|REXX}}: simplified code for inner DO loop.)
Line 277:
return int(''.join(perm))
return 0</lang>
 
===Python: Generator===
 
A variant which defines, in terms of concatMap, a generator of '''all''' digit-shuffle successors for a given integer:
 
<lang python>'''Digit-shuffle successors'''
 
from itertools import chain, islice, permutations
 
 
# digitShuffleSuccessors :: Int -> [Int]
def digitShuffleSuccessors(n):
'''Generator stream of all digit-shuffle
successors of n, where 0 <= n.
'''
def go(ds):
delta = int(''.join(list(ds))) - n
return [] if 0 >= delta else [delta]
for x in sorted(list(set(concatMap(go)(
list(permutations(str(n)))
)))):
yield n + x
 
 
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Up to 5 digit shuffle sucessors for each:'''
 
print(
fTable(main.__doc__)(str)(str)(
lambda n: take(5)(digitShuffleSuccessors(n))
)([
0,
9,
12,
21,
12453,
738440,
45072010
])
)
 
 
# GENERIC -------------------------------------------------
 
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
'''A concatenated list or string over which a function f
has been mapped.
The list monad can be derived by using an (a -> [b])
function which wraps its output in a list (using an
empty list to represent computational failure).
'''
return lambda xs: chain.from_iterable(map(f, xs))
 
 
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
f -> xs -> tabular string.
'''
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
 
 
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
return lambda xs: (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
 
# MAIN ---
if __name__ == '__main__':
main()</lang>
{{Out}}
<pre>Up to 5 digit shuffle sucessors for each:
0 -> []
9 -> []
12 -> [21]
21 -> []
12453 -> [12534, 12543, 13245, 13254, 13425]
738440 -> [740348, 740384, 740438, 740483, 740834]
45072010 -> [45072100, 45100027, 45100072, 45100207, 45100270]</pre>
 
=={{header|REXX}}==
9,659

edits