# NestWhile application

I have the function which take the last list in nested list, reduce it somehow in several ways so the length of list reduces and output new list wherein input list appended with defferent reduced lists. Maybe my explanation a little bit illegible but here is an example code:

cov = {{0, 3, 1, 2}};
l = 2;
detach = Function[{cov, l},
s = Last[cov];
Table[Append[cov,
Delete[ReplacePart[s, i -> l + Total[s[[i ;; i + 1]]]],
i + 1]], {i, 1, Length[s] - 1}]
];
detach[cov, l]

Output: {{{0, 3, 1, 2}, {5, 1, 2}}, {{0, 3, 1, 2}, {0, 6, 2}}, {{0, 3, 1, 2}, {0, 3, 5}}}


Now I need to apply recursively the same function to all lists of output list so for proposed example I shoud get the following result:

{{{0, 3, 1, 2}, {5, 1, 2}, {8, 2}, {12}},
{{0, 3, 1, 2}, {5, 1, 2}, {5, 5}, {12}},
{{0, 3, 1, 2}, {0, 6, 2}, {8, 2}, {12}},
{{0, 3, 1, 2}, {0, 6, 2}, {0, 10}, {12}},
{{0, 3, 1, 2}, {0, 3, 5}, {5, 5}, {12}},
{{0, 3, 1, 2}, {0, 3, 5}, {0, 10}, {12}}}


I tried to apply NestWhile or FixedPoint but did not succeed to get desired result.

You should have explained "apply recursively the same function to all lists of output list" clearer… anyway, the following code gives what you want:

Flatten[NestWhileList[Map[detach[#, l] &, #, {-3}] &, cov, Flatten@# != {} &][[-2]], 2]


Another apporoach:

NestWhile[Flatten[(detach[#, l] &) /@ #, 1] &, {cov}, Length@Last@Last@# != 1 &]


Here is an approach. It could be adapted for arbitrary starting lists. I have modified the detach function.

func[u_, num_] := Module[{a},
a = 2 + Plus @@@ Partition[#, 2, 1] &@Last[u];
Join[u, {Delete[ReplacePart[Last@u, num -> a[[num]]], num + 1]}]];
tab = Flatten[Table[{i, j, k}, {i, 3}, {j, 2}, {k, 1}], 2];
Fold[func, cov, #] & /@ tab


The last line yields:

{{{0, 3, 1, 2}, {5, 1, 2}, {8, 2}, {12}}, {{0, 3, 1, 2}, {5, 1,
2}, {5, 5}, {12}}, {{0, 3, 1, 2}, {0, 6, 2}, {8, 2}, {12}}, {{0, 3,
1, 2}, {0, 6, 2}, {0, 10}, {12}}, {{0, 3, 1, 2}, {0, 3, 5}, {5,
5}, {12}}, {{0, 3, 1, 2}, {0, 3, 5}, {0, 10}, {12}}}