Drill

ProblemsGo › patterns

The middle of the list

mediumpatternsSortingArraysMathGo

A dashboard shows a campaign’s typical daily spend, and “typical” is whatever lands in the middle once the days are sorted.

medianOf(values: list<int>) → float

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func medianOf(values []int) float64 {
	
}

Worked examples

CallResult
medianOf([]int{3, 1, 2})2.0
medianOf([]int{1, 2})1.5
medianOf([]int{5})5.0
medianOf([]int{5, 1, 4, 2})3.0

Hint

Sort a copy, not the caller’s list, then look at the middle pair or single value.

Reference solution in Go
func medianOf(values []int) float64 {
	xs := append([]int{}, values...)
	sort.Ints(xs)
	n := len(xs)
	if n == 0 {
		return 0.0
	}
	mid := n / 2
	if n%2 == 1 {
		return float64(xs[mid])
	}
	return (float64(xs[mid-1]) + float64(xs[mid])) / 2
}

The same problem in another language

More patterns problems in Go