Golang. Median


Today let’s remember what the median is and how to find it. The median is a number exactly in the middle of an ordered list. It is a very useful thing in statistics and it helps to see the real picture, not the average temperature in the hospital 🙂 For example, we have a list of 55, 1, 22, 7, 92… to find the median:

  1. we order it. We get: 1, 7, 22, 55, 92
  2. look for the one in the middle… that’s 22

If we have an even number of elements in the list, then the median is the average of the sum of two neighboring values. Anyway, here is the code of the simplest variant:

package main

import "fmt"

func main() {
	var median float64
	slice := []float64{3, 18, 49, 51, 121, 132}
	sliceLen := len(slice)
	center := sliceLen / 2

	if sliceLen%2 == 0 {
		median = (slice[center-1] + slice[center]) / 2
	} else {
		median = slice[center]
	}

	fmt.Println(median)
}

Arranging the list is a separate topic for discussion… there are many different sorting algorithms (the bubble method is far from the most efficient), we’ll look into them later in a separate post 😉

And here is another version of the program – where we already enter the values ourselves. This version works only with an odd number of terms:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func getN(r *bufio.Reader, nums int) int {

	for i := 1; nums > i; i++ {

		nRaw, err := r.ReadString('\n')
		if err != nil {
			panic(err)
		}

		n, err := strconv.Atoi(strings.TrimSpace(nRaw))
		if err != nil {
			panic(err)
		}

		if i > nums/2 {
			return n
		}
	}

	return 0
}

func main() {
	r := bufio.NewReader(os.Stdin)

	fmt.Println("How much numbers for calc?")

	numsR, err := r.ReadString('\n')
	if err != nil {
		panic(err)
	}
	nums, err := strconv.Atoi(strings.TrimSpace(numsR))
	if err != nil {
		panic(err)
	}

	n := getN(r, nums)

	fmt.Println(n)
}

Homework: finish this version so that it works correctly not only with odd values, but also with even values 😉

 


This entry was posted in Go (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.