daily pastebin goal
57%
SHARE
TWEET

Untitled

a guest Jun 12th, 2018 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "bufio"
  5.     "fmt"
  6.     "io"
  7.     "os"
  8.     "sort"
  9.     "strconv"
  10.     "strings"
  11. )
  12.  
  13.  
  14.  
  15. func main() {
  16.     reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024)
  17.  
  18.     nTemp, err := strconv.ParseInt(readLine(reader), 10, 64)
  19.     checkError(err)
  20.     n := int32(nTemp)
  21.  
  22.     a := make([]int, 0, n)
  23.    
  24.     for i := 0; i < int(n); i++ {
  25.         aItem, err := strconv.ParseInt(readLine(reader), 10, 64)
  26.         checkError(err)
  27.         insertSortedAscending(&a, int(aItem))
  28.         // fmt.Println(a)
  29.         median, err := getMedian(a)
  30.         if err == nil {
  31.             fmt.Printf("%.1f\n", median)
  32.         }
  33.     }
  34. }
  35.  
  36. func insertSortedAscending(a *[]int, f int) {
  37.     s:=*a
  38.     l:=len(s)
  39.     if l==0 { *a = append(*a, f) }
  40.  
  41.     i := sort.Search(l, func(i int) bool { return s[i] > f})
  42.  
  43.     *a = append(s[:i], append([]int{f}, s[i:]...)...)
  44. }
  45.  
  46. func getMedian(a []int) (float64, error) {
  47.     var arrayLength int = len(a)
  48.     if arrayLength == 0 {
  49.         return 0, MedianError{"can't find median of array length 0"}
  50.     }
  51.     if arrayLength % 2 == 0 {
  52.         var leftOfMiddle = a[arrayLength/2 - 1]
  53.         var rightOfMiddle = a[(arrayLength/2)]
  54.         return float64(leftOfMiddle + rightOfMiddle) / 2, nil
  55.     } else {
  56.         var middle = a[arrayLength/2]
  57.         return float64(middle), nil;
  58.     }
  59.        
  60. }
  61.  
  62. func readLine(reader *bufio.Reader) string {
  63.     str, _, err := reader.ReadLine()
  64.     if err == io.EOF {
  65.         return ""
  66.     }
  67.  
  68.     return strings.TrimRight(string(str), "\r\n")
  69. }
  70.  
  71. func checkError(err error) {
  72.     if err != nil {
  73.         panic(err)
  74.     }
  75. }
  76.  
  77. type MedianError struct {
  78.     Message string
  79. }
  80.  
  81. func (e MedianError) Error() string {
  82.     return fmt.Sprintf("%v", e.Message)
  83. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top