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 <
Go ahead and type this directly into the interpreter. The prompt is three spaces, so the indented lines are user input.
m=:-:@+/@(((2*+/\)I.+/)"1@(,:(\:i.@#))@[{"0 1(,:(\:i.@#))@])
The test data I used in my other answer:
1 1 1 1 m 1 2 3 4
2.5
1 1 2 1 m 1 2 3 4
3
1 2 2 5 m 1 2 3 4
3.5
1 2 2 6 m 1 2 3 4
4
The test data added to the question:
(>:,:[)i.10
1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9
(>:m[)i.10
6
(([+<&6),:>:)i.9
1 2 3 4 5 6 6 7 8
1 2 3 4 5 6 7 8 9
(([+<&6)m>:)i.9
6.5
i =: (2 * +/\) I. +/
First index such that total sum is greater than or equal to double the accumulated sum.
j =: ,: (\: i.@#)
List and its reverse.
k =: i"1 @ j @ [
First indices such that -see above- of the left argument and its reverse.
l =: k {"(0 1) j @ ]
Those indices extracted from the right argument and its reverse, respectively.
m =: -: @ +/ @ l
Half the sum of the resulting list.