1
$\begingroup$

I have a list of integers with the zero removed

Delete[Range[512/2, -512/2, -1], 257]

and I want to get the elements before and after a number within the list.

For example, if I want to get 5 elements before and after the number -255 in the list I should get:

{-250, -251, -252, -253, -254, -255, -256, 256, 255, 254, 253}

This makes the list look like, if we visualize it, a loop of numbers that goes on like:

.... 256 ... -256 , 256 ... -256 , 256...-256 ....

How can I do this?.

$\endgroup$
  • $\begingroup$ It might be Partition? $\endgroup$ – Αλέξανδρος Ζεγγ Sep 19 '18 at 15:37
  • $\begingroup$ I am not sure what Partition will look like but the result should be a list of numbers like {-250, -251, -252, -253, -254, -255, -256, 256, 255, 254, 253}. $\endgroup$ – jsid Sep 19 '18 at 15:48
3
$\begingroup$
ClearAll[f]
f[lst_, elem_, n_] := Module[{pos = Position[lst, elem][[1, 1]]}, 
  lst[[Mod[Range[pos - n, pos + n], Length @ lst, 1]]]]

Examples:

f[lst, -255, 5]

{-250, -251, -252, -253, -254, -255, -256, 256, 255, 254, 253}

f[lst, 251, 7]

{-255, -256, 256, 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.