This is a problem for which there must be an elegant and efficient solution which eludes me. The problem is best described with an example. Suppose you have the list $v$ of numbers from 1 to 10 in order, and another list, let us say, $a={5,6,8,1,3,4,7,9,2}$ which is a random sample of the numbers from 1 to 9. We will think of this second list a set of indices that will tell us how to associate the numbers in the original list $v$ so as to end up with a binary list of binary sublists, like the associated arguments of some binary product, if we may so think of it that way.
The first 5 tells us we must begin by associating 5,6 in $v$ to get
{1,2,3,4,{5,6},7,8,9,10}.
Then in $a$ comes 6, which tells us that we must produce the new list
{1,2,3,4,{{5,6},7},8,9,10}.
Then in $a$ comes 8, which tells us we must associate 8 and 9 to get
{1,2,3,4,{{5,6},7},{8,9},10}.
Then comes 1, and later 3, which tells us we must associate 1 and 2, and also 3 and 4, to get
{{1,2},{3,4},{{5,6},7},{8,9},10}.
Now it gets interesting, 4 comes next in $a$, so we must join the outermost sublist that ends with 4, and the next one:
{{1,2}, {{3,4},{{5,6}7}}, {8,9},10}.
Now comes 7. So we will join {{3,4},{{5,6},7}} with {8,9} in a binary list. We move on and rush a bit towards the final product. Then comes 9, which tells us to tack on 10 to the sublist ending in 9. Finally comes 2, which tells us now how to get the final result:
{{1,2}, {{ {{3,4},{{5,6},7}},{8,9} },10}}
So the problem is how to associate in general, the list of $n$ numbers (in an application they would be variables), using a random sample of a list of $n-1$ numbers, as I have described in the example. I feel I would almost like a one liner to do this. I am sure there is a very effective way to do this, but I can’t quite think of what it might be at the moment.
I thought it would be easier to work through an example than try to describe what I do. Then again, I am not very good with words. If this is not clear, I will try again.
Fold
of some kind e.gFold[g,Range[10],{5,6,8,1,3,4,7,9,2}]
butg
will be quite complicated. $\endgroup$