Generate a random binary number with a variable proportion of '1' bits

前端 未结 7 1779
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 16:55

I need a function to generate random integers. (assume Java long type for now, but this will be extended to BigInteger or BitSet later

7条回答
  •  有刺的猬
    2020-12-10 17:38

    Distribute proportional number of bits throughuot the number. Pseudocode:

    long generateNumber( double probability ){
      int bitCount = 64 * probability;
      byte[] data = new byte[64]; // 0-filled
    
      long indexes = getRandomLong();
    
      for 0 to bitCount-1 {
        do { 
          // distribute this bit to some postition with 0.
          int index = indexes & 64;
          indexes >> 6;
          if( indexes == 0 ) indexes = getRandomLong();
        } while ( data[index] == 0 );
        data[index] = 1;
      }
    
      return bytesToLong( data );
    }    
    

    I hope you get what I mean. Perhaps the byte[] could be replaced with a long and bit operations to make it faster.

提交回复
热议问题