简体   繁体   中英

How to distribute N regularly spaced bools in an array of M bools?

I am having the following problem that I cannot solve. Let's say I have an array of 100 bools, all false. I have a number N < 100 and I want to toggle N of these booleans to true, but so that they appear as regularly spaced as possible. This is obviously simple when N divides 100, but how to do it for instance if N = 53? I naively tried :

for(int i =0; i<53; ++i)
    std::cout << i*100/53 <<'\n';

to get 53 equaly distributed integers, and in this case I actualy have distincts integers, but I'm not sure this always works. Any pointers on this?

For the method you suggest, you will always get distinct integers for i * 100/X and (i + 1) * 100/X as long as X < 100 (as the difference is 100/X, which is > 1). So it's a simple proof by induction that all the integers you obtain this way are unique.

So this is a fine approach. The real question, which only you can answer, is how do you define equally distributed integers?

Perhaps for X > 2, you should always have i[0] and i[99] set to true and divide the space in between equally. For the special case of X = 1, set the middle element (50th or 51st) to true.

This is C#, but maybe something like this?

    static void Main( string[] args ) {

        bool[] bools = new bool[100];

        decimal incrementor = 100m / 53;
        decimal tracking = 0;
        for( int i = 0; i < 52; i++ ) {
            tracking += incrementor;
            bools[(int) Math.Round(tracking)] = true;
        }
    }

Find the largest number, P , less-than-or-equal-to N , for which P is a divisor of M .

At increments of P (beginning at index 0), place a number in the array.

The numbers in the array will be exactly as uniformly distributed as possible.

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