How to find the positions of a list of certain number in a number list

feelfree

Suppose I have a list of number: [0 0 1 1 1 0 1 1 0 1 0 0 0 1 1], which is composed of either 0 or 1,and my problem is how to find the beginning and ending positions of the number 1 in the list. Take the above list of number as an example, and the positions of a list of 1 are:

[2 4]
[6 7]
[9 9]
[13 14]

Using C++, the following method is implemented:

int main()
{   

    unsigned char charArray[15]={0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1};

    std::vector<std::pair<int,int> > posArray;

    int begPos=-1;
    int endPos=-1;
    for(int i=0; i<15; i++)
    {
        if(charArray[i] ==1)
        {
            if(begPos!=-1)
            {
                endPos++;
            }
            else
            {
                begPos=i;
                endPos=i;
            }
        }
        else
        {
            if(begPos != -1)
            {
                posArray.push_back(std::make_pair<int,int>(begPos,endPos));
                begPos=-1;
            }

        }

    }
    if(charArray[14] == 1)
    {
        posArray.push_back(std::make_pair<int,int>(begPos,endPos));
    }

    for(int i=0; i<posArray.size(); i++)
    {
        std::cout<<"( "<<posArray[i].first<<" , "<<posArray[i].second<<" )"<<std::endl;
    }
    return 0;
}

Are there more efficient solutions (either in time or in space) to this problem? Thanks.

Vlad from Moscow

The solution I will suggest is not more efficient but looks better.:)

Try the following

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <utility>
#include <functional>

int main() 
{
    unsigned char charArray[] = 
    { 
        0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1
    };
    std::vector<std::pair<int,int> > posArray;

    auto first = std::begin( charArray );

    while ( ( first = std::find( first, std::end( charArray ), 1 ) ) != std::end( charArray) )
    {
        auto last = std::find_if( first, std::end( charArray ), 
                                  std::bind2nd( std::not_equal_to<int>(), 1 ) );

        posArray.push_back( { std::distance( charArray, first ),
                              std::distance( charArray, last ) - 1 } );
        first = last;                             
    }

    for ( auto &p : posArray ) std::cout << '[' << p.first 
                                         << ' ' << p.second
                                         << ']' << std::endl;

    return 0;
}

The output is

[2 4]
[6 7]
[9 9]
[13 14]

If the array consists only from 0 and 1 then you may substitute this statement

    auto last = std::find_if( first, std::end( charArray ), 
                              std::bind2nd( std::not_equal_to<int>(), 1 ) );

for this one

    auto last = std::find( first, std::end( charArray ), 0 );

In this case the loop will look like

while ( ( first = std::find( first, std::end( charArray ), 1 ) ) != std::end( charArray) )
{
    auto last = std::find( first, std::end( charArray ), 0 ); 

    posArray.push_back( { std::distance( charArray, first ),
                          std::distance( charArray, last ) - 1 } );
    first = last;                             
}

To write a more efficient code you have to reserve memory for the vector.

For example

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <utility>
#include <functional>

int main() 
{
    unsigned char charArray[] = 
    { 
        0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1
    };
    std::vector<std::pair<int,int> > posArray;

    size_t n = std::inner_product( std::next( std::begin( charArray ) ), 
                                   std::end( charArray ), 
                                   std::begin( charArray ), 
                                   0ul, 
                                   std::plus<size_t>(),
                                   std::greater<char>() );

   n += charArray[0] == 1;

    posArray.reserve( n );

    auto first = std::begin( charArray );

    while ( ( first = std::find( first, std::end( charArray ), 1 ) ) != std::end( charArray) )
    {
        auto last = std::find( first, std::end( charArray ), 0 ); 

        posArray.push_back( { std::distance( charArray, first ),
                              std::distance( charArray, last ) - 1 } );
        first = last;                             
    }

    for ( auto &p : posArray ) std::cout << '[' << p.first 
                                         << ' ' << p.second
                                         << ']' << std::endl;

    return 0;
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Find count of number of pairs in the list

분류에서Dev

Prolog: Count number of times e appears in a list in odd positions

분류에서Dev

C# Linq, Find highest number from list using linq

분류에서Dev

I have JSON Object, with this object i need to find the ID Number of "xxxEmployeeCategory "T" and list the list in an Array

분류에서Dev

List files appended with an order number

분류에서Dev

Finding number of unique elements in the list

분류에서Dev

List a number of copies per book

분류에서Dev

ansible check max number list

분류에서Dev

counting the number of values in a python list

분류에서Dev

How can I change the number of items that end up in a list

분류에서Dev

Need to find list of scripts that uses a certain file

분류에서Dev

How to find the number of columns in the bindingsource?

분류에서Dev

How to find the missing number in a sequence

분류에서Dev

How to find gaps in list?

분류에서Dev

Finding the closest number to a target sum of a list

분류에서Dev

Create 'number of matches' list using python

분류에서Dev

python 2.7 select words in list prior to number

분류에서Dev

Counting even number haskell with list comprehension?

분류에서Dev

random number from list based off percentage

분류에서Dev

Random distribution of items in list with exact number of occurences

분류에서Dev

List all .txt file and count number of column

분류에서Dev

git list remote branch, order by number of commits

분류에서Dev

List Comprehension Instead of Nested For Loops for Repeated Number List

분류에서Dev

python, rank a list of number/string (convert list elements to ordinal value)

분류에서Dev

Invert bits on even positions from binary number

분류에서Dev

How to find number of Subdirectories under a given directory

분류에서Dev

How to find the number of elements in a set? CPLEX OPL

분류에서Dev

How to Find IMEI Number from Windows 7?

분류에서Dev

How to find the number of keys created in map part?

Related 관련 기사

  1. 1

    Find count of number of pairs in the list

  2. 2

    Prolog: Count number of times e appears in a list in odd positions

  3. 3

    C# Linq, Find highest number from list using linq

  4. 4

    I have JSON Object, with this object i need to find the ID Number of "xxxEmployeeCategory "T" and list the list in an Array

  5. 5

    List files appended with an order number

  6. 6

    Finding number of unique elements in the list

  7. 7

    List a number of copies per book

  8. 8

    ansible check max number list

  9. 9

    counting the number of values in a python list

  10. 10

    How can I change the number of items that end up in a list

  11. 11

    Need to find list of scripts that uses a certain file

  12. 12

    How to find the number of columns in the bindingsource?

  13. 13

    How to find the missing number in a sequence

  14. 14

    How to find gaps in list?

  15. 15

    Finding the closest number to a target sum of a list

  16. 16

    Create 'number of matches' list using python

  17. 17

    python 2.7 select words in list prior to number

  18. 18

    Counting even number haskell with list comprehension?

  19. 19

    random number from list based off percentage

  20. 20

    Random distribution of items in list with exact number of occurences

  21. 21

    List all .txt file and count number of column

  22. 22

    git list remote branch, order by number of commits

  23. 23

    List Comprehension Instead of Nested For Loops for Repeated Number List

  24. 24

    python, rank a list of number/string (convert list elements to ordinal value)

  25. 25

    Invert bits on even positions from binary number

  26. 26

    How to find number of Subdirectories under a given directory

  27. 27

    How to find the number of elements in a set? CPLEX OPL

  28. 28

    How to Find IMEI Number from Windows 7?

  29. 29

    How to find the number of keys created in map part?

뜨겁다태그

보관