#pragma once

// Bidirectional CDF sampling [Ciklabakkal et al. 2022, Algorithm 1].
// Returns the same index as inverse cdf sampling with the same u, i.e. the j such that
//     sum_{i<j} w_i <= u * W < sum_{i<=j} w_i,
// in a single pass over the weights, read from both ends of the list, without storing them
// and without knowing their sum W in advance.
// weight(k) returns the weight of candidate k in [0, n). Requires n > 0, u in [0, 1)
// and a positive total weight.

template <typename Weight>
int bidirectional_cdf_sample(const Weight& weight, const int n, const float u)
{
    int front = 0, back = n - 1;
    double wfront = weight(front), wback = weight(back);   // running sums from both ends
    while(front != back)
    {
        if(wfront <= u * (wfront + wback))
            wfront += weight(++front);
        else
            wback += weight(--back);
    }
    return front;
}
