6
$\begingroup$

A very short version of my list named "fire" is

fire = {{0, 0, 0, 20, 0, 0}, {0, 0, 0, 20, 0, 0}, {0, 0, 20, 20, 0, 0}}.

For the first sublist Length[TakeWhile[fire[[1]], # < 20 &]], calculates the number of preceding "0" before 20 shows up. In this case I get 3. The number of preceding 0 before 20 or the end of the sublist shows up is my ultimate goal.

Since my true list has 1000 of these sublists of six numbers I tried to map the function Length[TakeWhile[fire...]. However, MapApply or Map did not work. The problem seems to identy the subsequent elements of fire within the expression. Any help is highly appreciated.

$\endgroup$
10
  • 2
    $\begingroup$ Length@First@SplitBy[#, 20] & /@ fire $\endgroup$
    – martin
    Commented Aug 19, 2022 at 21:22
  • 1
    $\begingroup$ f[x_] := Length[TakeWhile[x, # < 20 &]]; f /@ fire $\endgroup$
    – martin
    Commented Aug 19, 2022 at 21:23
  • $\begingroup$ Unclear: are 0s the only possible entries before the 20? $\endgroup$ Commented Aug 19, 2022 at 21:27
  • 1
    $\begingroup$ Does the built-in work? LengthWhile[#, EqualTo[0]] & /@ fire? Assuming the only possible values are 0 or 20, at least, if the lists here are good examples. $\endgroup$
    – thorimur
    Commented Aug 19, 2022 at 21:43
  • 1
    $\begingroup$ Let me give my 5 cents into this discussion: Position[fire[[1]], 20][[1, 1]] - 1 yields the expected 3. $\endgroup$ Commented Aug 20, 2022 at 6:49

2 Answers 2

1
$\begingroup$
list = {{0, 0, 0, 20, 0, 0}, {0, 0, 0, 20, 0, 0}, {0, 0, 20, 20, 0, 0}};

Using SequenceCount

SequenceCount[#, {0 .., Except[0]}, Overlaps -> True] & /@ list

{3, 3, 2}

Another test

SequenceCount[ {{1}, {0, 1}}, {0 .., Except[0]}, Overlaps -> True] & /@ list

{0, 1}

$\endgroup$
1
$\begingroup$
list = {{0, 0, 0, 20, 0, 0}, {0, 0, 0, 20, 0, 0}, {0, 0, 20, 20, 0, 0}};

Using Replace at level 1 and SequencePosition:

Replace[list, x_ :> Length@SequencePosition[x, {0 .., 20}], {1}]

{3, 3, 2}

$\endgroup$

Your Answer

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

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