Group Abstract Group Abstract

Message Boards Message Boards

0
|
9.5K Views
|
15 Replies
|
1 Total Like
View groups...
Share
Share this post:

[?] Count the zeros between the ones in a list?

Posted 8 years ago
POSTED BY: Chiel Geeraert
15 Replies
Posted 8 years ago
POSTED BY: Chiel Geeraert

To the collection of possible approaches here comes one more:

data = {0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0};
ComponentMeasurements[Image[1 - {data}], "Count"]
POSTED BY: Henrik Schachner
POSTED BY: Raspi Rascal
Posted 8 years ago
POSTED BY: Chiel Geeraert

We would like to see your workaround solution.

POSTED BY: Raspi Rascal
Posted 8 years ago

Here is my workaround :

In[20]:= Test = {1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
    0, 0, 0, 0, 1, 0, 0};
(* The desired output is the number of zero's between the ones so
{4,2,5,7} *)

In[15]:= Test = Flatten[Position[Test, 1]]

Out[15]= {1, 6, 9, 15, 23}

In[17]:= Result = 
 Table[Test[[k + 1]] - Test[[k]] - 1, {k, 1, Length[Test] - 1}]

Out[17]= {4, 2, 5, 7}
POSTED BY: Chiel Geeraert
Posted 8 years ago

A slight variation:

Differences@Flatten@Position[Test, 1] - 1
POSTED BY: Hans Milton
Posted 8 years ago
POSTED BY: Chiel Geeraert
Posted 8 years ago

Thank you very much. In the meantime I have found a simple , not very sophisticated, workaround solution but it works.

I will try your suggestion and try to understand it.

Best regards, Chiel Geeraert

POSTED BY: Chiel Geeraert
POSTED BY: Raspi Rascal

Can be done even shorter:

SequenceCases[{1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0}, x : {0 ..} :> Length[x]]
POSTED BY: Sander Huisman
Posted 8 years ago
POSTED BY: Chiel Geeraert
t=FromDigits[Test]//IntegerString;
StringCases[t,x:("1"~~"0"..~~"1"):>StringLength[x]-2,Overlaps->True]

Maybe faster for large list?

POSTED BY: Raspi Rascal

You may try SequenceSplit:

l = {1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0};
SequenceSplit[l, {1 ..}]
Map[Length, %]

This counts also the trailing three zeros. You can correct that problem if you really need it.

POSTED BY: Gianluca Gorni
Posted 8 years ago
POSTED BY: Chiel Geeraert
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard