import torch


def systematic_resample(weights):
    """ Performs the systemic resampling algorithm used by particle filters.
    This algorithm separates the sample space into N divisions. A single random
    offset is used to to choose where to sample from for all divisions. This
    guarantees that every sample is exactly 1/N apart.
    Parameters
    ----------
    weights : list-like of float
        list of weights as floats
    Returns
    -------
    indexes : ndarray of ints
        array of indexes into the weights defining the resample. i.e. the
        index of the zeroth resample is indexes[0], etc.
    """
    N = len(weights)

    # make N subdivisions, and choose positions with a consistent random offset
    #positions = (random() + np.arange(N)) / N
    positions = (torch.rand(1) + torch.arange(N)) / N

    #indexes = np.zeros(N, 'i')
    indexes=torch.zeros(N,dtype=torch.int32)
    #cumulative_sum = np.cumsum(weights)
    cumulative_sum = torch.cumsum(weights,dim=0)
    i, j = 0, 0
    while i < N:
        if positions[i] < cumulative_sum[j]:
            indexes[i] = j
            i += 1
        else:
            j += 1
    return indexes