Code Golf: Shortest code to find a weighted median?

后端 未结 7 623
眼角桃花
眼角桃花 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

    Something like this? O(n) running time.

    for(int i = 0; i < x.length; i++)
    {
    sum += x[i] * w[i];
    sums.push(sum);
    }
    
    median = sum/2;
    
    for(int i = 0; i < array.length - 1; i++)
    {
        if(median > sums[element] and median < sums[element+1]
             return x[i];
        if(median == sums[element])
             return (x[i] + x[i+1])/2
    }
    

    Not sure how you can get two answers for the median, do you mean if sum/2 is exactly equal to a boundary?

    EDIT: After looking at your formatted code, my code does essentially the same thing, did you want a MORE efficient method?

    EDIT2: The search part can be done using a modified binary search, that would make it slightly faster.

    index = sums.length /2;
    finalIndex = binarySearch(index);
    
    int binarySearch(i)
    {
        if(median > sums[i+1])
        {
            i += i/2
            return binarySearch(i);
        }
        else if(median < sums[i])
        {
            i -= i/2
            return binarySearch(i);
        }
        return i;
    }
    

    Will have to do some checking to make sure it doesn't go on infinitely on edge cases.

提交回复
热议问题