简体   繁体   中英

optimize binary increment loop

Earlier today I asked a question regarding getting every possible combinations and I was given a good hint on using a binary loop, after some thoughts into it I came up with the following code in C++:

    vector<bool>binary(size,0);

bool filled=false;
while(filled==false)
{

    bool setdigit=true;
    for(int k=0;k<size;k++)
    {
        if(setdigit==true)
        {
            if(binary[k]==false) 
            {
                    binary[k]=true;
                    setdigit=false;
            }
            else //when the digit is already true
            {
                binary[k]=false;
            }
        }
    }
    for(int i=0;i<size;i++)
    {
        if(binary[i]==false) 
            {
                filled=false;
                break;
        }
        else filled=true;
    }
}

The code seems to work but the way to test whether the binary increment is finished is very badly coded, how should i go to improve the exit condition or even the looping process?

pseudo code:

for (i=0;i<2^size;i++)
   binary = std::bitset(i);  /* the bits of i are the bits you are looking for */

Your setdigit is useless. you may remove it, remove the condition, and replace the assignation to false by a break . So the loop would be

for(int k = 0; k < size; k++)
{
    if (binary[k] == false) 
    {
        binary[k] = true;
        break;
    }
    else // when the digit is already true
    {
        binary[k] = false;
    }
}

You may then change your while (filled /* has only true */)
by a do {} while(binary_is_false /* has only false */)
to allow to do the check directly inside the increment.

You may finally split your code into function to obtain something like: ( https://ideone.com/dmQwFc )

bool increase(std::vector<bool>& v)
{
    for (std::size_t i = 0; i != v.size(); ++i) {
        v[i] = !v[i];
        if (v[i] == true) {
            return true;
        }
    }
    return false; // v contains only false values now.
}

int main()
{
    std::vector<bool> v(5);

    do {
        // Do some job as printing vector content:
        for (std::size_t i = 0; i != v.size(); ++i) {
            std::cout << v[i] << " ";
        }
        std::cout << std::endl;
    } while (increase(v));
    return 0;
}

You can change the code:

for(int i=0;i<size;i++)
    {
        if(binary[i]==false) 
            {
                filled=false;
                break;
        }
        else filled=true;
    }

by

filled = (find(binary.begin(), binary.end(), false) == binary.end())

you need to include <algorithm> for this work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM