0

I'm using c++ but really just need an idea how to do this I should be able to come up with my own code. I know there are 112 possible combinations, but I'm trying to find a way to generate them all possibly an array without having to do it manually. it doesn't have to be an array, I can easily make it an array if needed, just need to generate all the binary numbers between 0 and 128 containing exactly 5 on bits.

bool/int bit[8];

whatever works where

bit[7]+bit[6]+bit[5]+bit[4]+bit[3]+bit[2]+bit[1]+bit[0]=5;
bool/int bits[8][112];

trying to figure out how to do this in a loop I've been googling and haven't found anything close to what I'm trying to do, any help will be greatly appreciated.

RCaetano
  • 642
  • 1
  • 8
  • 23
  • You can use an integral type to count from 0 to 128, and each time, separate the iterator into bits with a bitmask, and count the number of bits that are 1. – millinon Sep 29 '16 at 15:54
  • If you don't want to do that for large amounts of numbers, you could try it differently by enumerating 0-128 and [filter all which have more than 5 set bits using a bit counting algorithm](http://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer). Directly generating them may be a more complex task. – makadev Sep 29 '16 at 15:57
  • sorry the question should be an 8 bit binary number with exactly 5 on bits – logicandchaos Sep 29 '16 at 17:27

1 Answers1

0

I figured it out

#include <iostream>

using namespace std;

int binArray[8]={0,0,0,0,0,0,0,0};

int main(){
    for(int i=0;i<112;i++){
        do{
            binArray[7]++;
            for(int b=7;b>-1;b--){
                if(binArray[b]==2){
                    binArray[b]=0;
                    binArray[b-1]++;
                }
            }
        }
        while(binArray[7]+binArray[6]+binArray[5]+binArray[4]+binArray[3]+binArray[2]+binArray[1]+binArray[0]!=5);
        for(int j=0;j<8;j++){
            cout << binArray[j] << " ";
        }
        cout << endl;
    }

    return 0;
}