Code Golf: Shortest code to find a weighted median?

后端 未结 7 606
眼角桃花
眼角桃花 2021-01-03 08:23

My try at code golfing.

The problem of finding the minimum value of ∑W_i*|X-X_i| reduces to finding the weighted median of a list of x[i] with weights <

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 09:08

    So, here's how I could squeeze my own solution:, still leaving some whitespaces:

        int s = 0, i = 0;
        for (; i < n; s += w[i++]) ;
        while ( (s -= 2*w[--i] ) > 0) ;
        a  =  x[i]  +  x[ !s && (w[i]==w[i-1]) ? i-1 : i ]; 
    

提交回复
热议问题