1

Given a sorted table, how can I find the position of non consecutive numbers in the first column of the table?

list = {{1, 3, 5}, {3, 3, 5}, {4, 3, 5}, {5, 3, 5}, {7, 3, 5}}//MatrixForm

enter image description here

How to do I find the row position of the first non-consecutive number in column one?
How to do I find the row position of the last non-consecutive number in column one?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257

2 Answers2

5

I would rather define:

list = {{1, 3, 5}, {3, 3, 5}, {4, 3, 5}, {5, 3, 5}, {7, 3, 5}};

If you prefer for some reasons your own definition you can use list[[1]] instead of list. To extract the first column use First@Transpose@list or list[[All, 1]], for the last column use Last@Transpose@list, for k-th column e.g. list[[All, k]].

Then there are many ways, let's show a few of them:

Position[ KroneckerDelta /@ (Differences[ First @ Transpose @ list] - 1), 0] + 1
{{2}, {5}}

Instead of mapping KroneckerDelta we could use simply Unitize (as pointed out by J.M.), since it is Listable. Moreover we could substitute Differences with subtruction of Rest and Most to get the proper result:

Position[ Unitize[ Subtract @@ Through@{Rest, Most}@First@Transpose@list - 1], 1] + 1

another method without Apply for extracting non-consecutive numbers of the last column:

Position[ Total[ Through @ { Rest, - Most @ # &} @ Last @ Transpose @ list], 0] + 1
 {{2}, {3}, {4}, {5}}

A related discussion useful for the problem at hand you can find reading answers to this question Find zero crossing in a list.

Artes
  • 57,212
  • 12
  • 157
  • 245
2

EDIT

My original code was padding with 0 was specific for test not general...apologies.

In the test example the position of the non-consecutive numbers in the first clumn are 2 and 5 (correct me if I am misinterpreting).

Applying:

fun[u_List] := 
 Position[Differences@PadLeft[u, Length@u + 1,u[[1]]-1], _?(# > 1 &)]

to the first column finds positions of element whose preceding element is > 1.

i.e.

fun[list[[;;,1]]]

yields:

{{2}, {5}}
ubpdqn
  • 60,617
  • 3
  • 59
  • 148