集册 Java实例教程 获取随机未设置位

获取随机未设置位

欢马劈雪     最近更新时间:2020-01-02 10:19:05

488
获取随机未设置位

/*

 This file is part of p300.



 p300 is free software: you can redistribute it and/or modify

 it under the terms of the GNU General Public License as published by

 the Free Software Foundation, either version 3 of the License, or

 (at your option) any later version.


 p300 is distributed in the hope that it will be useful,

 but WITHOUT ANY WARRANTY; without even the implied warranty of

 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

 GNU General Public License for more details.


 You should have received a copy of the GNU General Public License

 along with p300.  If not, see <http://www.gnu.org/licenses/>.

 */

import java.util.BitSet;


public class Main{
/* from 
时 代 J a v a 公 众 号 - N o w J a v  a . c o m*/

    public static int getRandomUnsetBit(BitSet bs, int len) {

        if (bs.cardinality() >= len) {

            // failure

            return 0;

        }


        // try 20 times to see a random one

        for (int i = 0; i < 20; i++) {

            int idx = RandomGenerator.getInt(0, len);/*from 时   代     Java  公  众  号 - nowjava.com*/


            if (!bs.get(idx))

                return idx;

        }


        // trying randomly did not work      

        int numberOfUnsetBits = len - bs.cardinality();

        int numberOfUnsetBitToPick = RandomGenerator.getInt(0,

                numberOfUnsetBits);


        int j = numberOfUnsetBitToPick;

        for (int i = 0; i < len; i++) {

            if (!bs.get(i)) {

                // unset bit

                j--;


                if (j <=
展开阅读全文