Message Boards Message Boards

1
|
5131 Views
|
2 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Test to output only non-repeated elements in a repeating list?

Posted 11 years ago
I have a Nested List that returns a list of numbers which sometimes (but not always) begin to repeat.  Here is an example of an instance where the numbers begin repeating : 

In[3]:= NestList [ love[#, 37, 42] &, 1, 42 ]
Out[3]= {1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16}

Here, the numbers 1, 37, 16, 18, 10 begin to repeat.  I need to run the NestList a full 42 times, because sometimes it returns all unique numbers.  But in the cases where numbers repeat, I want to take only the unrepeated numbers and the first repeated number, then stop.  For instance, in the example above, I want {1, 37, 16, 18, 10, 1} as my output.  My Question: Is there a simple test I can run or some other means to achieve this? 
      Also relevant: i do not know how long the repeated sequence will be until execute the input.

Thank you! Please forgive me if it is a very simple fix.
POSTED BY: Bryan Lettner
2 Replies
Posted 11 years ago
Thank you Bill.  Works great.
POSTED BY: Bryan Lettner
Posted 11 years ago
 In[1]:= v = {1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16, 18, 10,
    1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16, 18, 10, 1, 37, 16};
    nonRepeated[v_] := Module[{i = 1},
       While[Drop[v, i] != Drop[v, -i] && i < Length[v], i++];
       If[i < Length[v], Take[v, i + 1], v]
    ];
 
 In[3]:= nonRepeated[v]
 
Out[3]= {1, 37, 16, 18, 10, 1}

In[4]:= nonRepeated[{1, 2, 3, 4, 5}]

Out[4]= {1, 2, 3, 4, 5}
But this depends on the repetitions beginning with the first item in your list.
Test this carefully with all kinds of lists before you depend on it.
POSTED BY: Bill Simpson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract