Hi, I'm Ataias Reis

Programmer, made in Brazil, Alma mater University of Brasilia

30 days of code in Go: Day 14 - Weighted mean

Hi there! Today’s problem is quite simple. The challenge is to compute the weighted mean given two arrays. The first input is $N$, the number of elements of each array, and then the first array is given and then the second whose components are the weights. My solution is given below.

package main

import "fmt"

func main() {
  N := 0
  fmt.Scanf("%d", &N)
  a := make([]float64, N)
  b := make([]float64, N)

  for i := 0; i < N; i++ {
    fmt.Scanf("%f", &a[i])
  }

  for i := 0; i < N; i++ {
    fmt.Scanf("%f", &b[i])
  }

  numerator := 0.0
  denominator := 0.0
  for i := 0; i < N; i++ {
    numerator += a[i] * b[i]
    denominator += b[i]
  }

  mean := numerator / denominator
  fmt.Printf("%.1f\n", mean)
}

The only problem I had was that I forgot to read the arrays initially 😆. The rest of the code was quite easy given what I learned so far. I made use of type inference in Go which is quite nice. If you have any comments, don’t hesitate to post it on disqus! See you!

Tags
comments powered by Disqus