4
$\begingroup$

I want to find in a list of couples the positions of the ones with consecutive items:

z={{1, 2}, {2, 3}, {3, 6}, {6, 7}, {7, 10}, {10, 11}, {11, 14}, {14, 19}, {19, 20}, {20, 25}, {25, 28}, {28, 29}, {29, 32}, {32, 37}, {37, 42}, {42, 43}, {43, 48}, {48, 51}, {51, 52}, {52, 57}, {57, 60}, {60, 65}, {65, 72}, {72, 75}, {75, 76}, {76, 79}, {79, 80}, {80, 83}, {83, 96}, {96, 99}, {99, 104}, {104, 105}, {105, 114}, {114, 115}, {115, 120}, {120, 125}, {125, 128}, {128, 133}, {133, 138}, {138, 139}, {139, 148}, {148, 149}, {149, 152}, {152, 153}, {153, 164}, {164, 175}, {175, 178}, {178, 179}}
Flatten@Position[z, _?(#[[2]] == #[[1]] + 1 &)]

I have used this previously but strangely I get:

Part::partd: Part specification List[[2]] is longer than depth of object.
Part::partd: Part specification List[[2]] is longer than depth of object.
Part::partd: Part specification List[[2]] is longer than depth of object.
General::stop: Further output of Part::partd will be suppressed during this calculation.

{1, 2, 4, 6, 9, 12, 16, 19, 25, 27, 32, 34, 40, 42, 44, 48}

The answer is correct but I don't understand the messages above.

$\endgroup$
4
  • 4
    $\begingroup$ Try: Position[z, {x_, y_} /; y == x + 1] $\endgroup$ Mar 24 at 9:24
  • 3
    $\begingroup$ Try Position[z, _?(Function[Echo[#];#[[2]] == #[[1]] + 1])] to see where the messages come from. $\endgroup$ Mar 24 at 11:28
  • 1
    $\begingroup$ Try: Position[z, x_List /; Last[x] == First[x] + 1] $\endgroup$ Mar 24 at 14:49
  • $\begingroup$ Also {z[[All,1]]+1, z[[All,2]]}//Transpose//MapApply[Subtract]//Position[0] $\endgroup$
    – user1066
    Mar 24 at 17:05

1 Answer 1

5
$\begingroup$

The following will solve your problem:

Flatten@Position[z, _?(#[[2]] == #[[1]] + 1 &), {1}, Heads -> False]

The more idiomatic solution has been written by Daniel Huber in the comments. Building on that:

Position[z, {a_Integer, b_Integer} /; b == a + 1, {1}]

Remember that the output of Position is directly usable with the Extract command.

$\endgroup$
1
  • 2
    $\begingroup$ (+1) this method work for the case when Length[z]==2. $\endgroup$
    – cvgmt
    Mar 24 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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