Create boolean vector of length n with k true values well dispersed
Asked Answered
C

1

-1

The problem is to create boolean vector of length n with k true entries (and n-k false entries) well dispersed in the vector.

If k = 5 and n = 8 manually created solutions are [1 0 1 1 0 1 0 1] or [1 0 1 0 1 0 1 1] etc.

An example for a vector with entries that are not well dispersed would be [1 1 1 1 1 0 0 0 0].

A possible criterium for "well-dispersedness" is having alternating blocks of zeros and ones of roughly the same length - specifically with one-blocks of size floor(n/k) or floor(n/k) + 1 and zero-blocks of size floor(n/(n-k)) or floor(n/(n-k)) + 1.

How to create such a vector?

Cadenza answered 8/11, 2019 at 16:8 Comment(1)
A possible criterion ... There are many possible criteria, you must specify one and also explain what difficulty you're having with the problem.Unguinous
W
1

Get the simplest implementation of Bresenham algorithm, and simulate drawing of line segment with end coordinates (0,0)-(ones,zeros). This is just error-propagation approach.

When algorithm generates change of X-coordinate (X-step), it corresponds to 1-entry, Y-step corresponds to zero bit.

def Distribute(ones, zeros):
    leng = ones + zeros
    err = leng // 2
    res = []
    for i in range(0, leng):
        err = err - ones
        if err < 0 :
            res.append(1)
            err = err + leng
        else:
            res.append(0)
    print(res)

Distribute(5,3)
[1, 0, 1, 0, 1, 1, 0, 1]
Weakling answered 8/11, 2019 at 19:54 Comment(3)
That is nice! Is this version of Bresenham's algorithm guaranteed to create a vector with exact k number of ones or do I need to check the result?Cadenza
From this an answer for https://mcmap.net/q/241117/-how-to-merge-2-vectors-alternating-indexes can be derivedCadenza
@mschauer I hope - yes, random tests passed. But it is possible to use another implementation with explicit loop by XWeakling

© 2022 - 2024 — McMap. All rights reserved.