list/sequence problem: a 'keep' list to a list of

list/sequence problem: a 'keep' list to a list of

Post by DrMajorBo » Sun, 08 Mar 2009 16:40:03


keepPrior = {False, True, False, True, False, False, True, True, True,
False, True};
counter = 0;
Rest@FoldList[(counter++; If[#2, Flatten@{#1, counter}, {counter}]) &,
dummy, keepPrior]

{{1}, {1, 2}, {3}, {3, 4}, {5}, {6}, {6, 7}, {6, 7, 8}, {6, 7, 8,
9}, {10}, {10, 11}}

or

counter = 0;
Rest@FoldList[(counter++; If[#2, Append[#1, counter], {counter}]) &,
dummy, keepPrior]

{{1}, {1, 2}, {3}, {3, 4}, {5}, {6}, {6, 7}, {6, 7, 8}, {6, 7, 8,
9}, {10}, {10, 11}}

Bobby






--
XXXX@XXXXX.COM
 
 
 

list/sequence problem: a 'keep' list to a list of

Post by DrMajorBo » Sun, 08 Mar 2009 16:40:15

Sorry, that fails (with "dummy" as second argument to FoldList) if the
first element of keepPrior is True.

You haven't specified what you want to do in that case, but maybe this
would do:

keepPrior = {True, False, True, False, True, False, False, True, True,
True, False, True};
counter = 0;
Rest@FoldList[(counter++;
If[#2, Append[#1, counter], {counter}]) &, {}, keepPrior]

{{1}, {2}, {2, 3}, {4}, {4, 5}, {6}, {7}, {7, 8}, {7, 8, 9}, {7, 8, 9,
10}, {11}, {11, 12}}

Bobby

On Fri, 06 Mar 2009 14:04:10 -0600, DrMajorBob < XXXX@XXXXX.COM >






--
XXXX@XXXXX.COM

 
 
 

list/sequence problem: a 'keep' list to a list of

Post by Miles Rain » Sun, 08 Mar 2009 16:41:21

Doctor (or is it Sir?),

Very nice, thanks much. I was pretty sure there had to be a more concise,
canonical way to accomplish the task. As you surmised, the first element
would always be True.

You have prompted me to gain a better understanding and appreciation of
FoldList. I've only been using Mathematica for ~10 years, so I still have a lot to
learn :)

Miles