Suppose I have a list of integers like so:
list = {1,2,5,6,8,10,11,12,14,16,17,18,19};
I'd like a function that will take this list and return a new list with the numbers that are "lonely" being removed, with lonely numbers being those that have no neighbor to their left or their right, where a neighbor is a number whose difference to the next/previous number in the list is equal to 1. In the example given above this would be the numbers "8" and "14", which have no neighbors, so the list returned would be {1,2,5,6,10,11,12,16,17,18,19}
.
Currently I have an ugly Do
loop for this operation, but there must be a better way! We can presume the list is already sorted since it's trivial to add a Sort
.
PatternSequence[]
? That should be usable for checking neighbors… $\endgroup$ – J. M.'s ennui♦ May 29 '15 at 0:06