prolog - Split Number in its digits, grouped in all possble ways -
i have number, let's 123, , want generate set of possible ways split it:
[[1, 23], [12, 3], [1, 2, 3]].
i have thought of creating powerset of [1,2,3]:
?- findall(powerset, powerset([1,2,3], powerset), z). z = [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]].
then combining sets , checking append/3
if concatenation initial set [1,2,3], i.e
[[1], [2, 3]] -> [1, 23] [[1, 2], [3]] -> [12, 3] [[1], [2], [3]] -> [1, 2, 3]
do think of simpler (more elegant) solution?
i use predicate gnu prolog powerset modification
powerset(l, [h|t]):- append([h|t], _, l). powerset([_|l], p):- powerset(l, p).
no need use findall/3
here---use dcg!
int_split(x) --> int_split__aux(x,10,[]). int_split__aux(x,p,ds) --> ( { x =:= 0 } -> [ds] ; { x < p } -> [[x|ds]] ; { x0 x mod p, x1 x div p }, int_split__aux(x1,10,[x0|ds]), { p1 p*10 }, int_split__aux(x,p1,ds) ).
sample use:
?- phrase(int_split(123),zss). zss = [[1,2,3], [12,3], [1,23], [123]]. ?- phrase(int_split(1234),zss). zss = [[1,2,3,4], [12,3,4], [1,23,4], [123,4], [1,2,34], [12,34], [1,234], [1234]].
Comments
Post a Comment