I have an array like this:
0011011100011111001
I’d like to find the longest sequence of 1’s in this array, keeping note of the length and position of the starting point, here the length would be 5 and the starting point is 12.
Any ideas for how to go about this?
You can set a starting position and length initially to zero, then go through the array elements one by one, keeping track of the transitions between
1and0with a simple state machine.The state table looks like this:
Since you’re only interested in
1sequences, the initial state haslastNumset to zero to ensure a1at the start correctly begins a run. We also set up the initial “largest run to date” to have a size and position of zero to ensure it gets overwritten by the first real run.There’s a special edge case to this method because we have to detect if the final number in the list is
1– if so, it means there will have been no1 -> 0transition at the end of the list for checking the final run of1numbers.Since we will have exited the loop without checking that final run, we do a final check as if we were transitioning from
1to0.The pseudo-code goes something like this. First, the initialisation of all variables:
Then we can simply iterate over each number in the list and detect transitions as per the diagram above:
Then, finally, handling of the afore-mentioned edge case: