Vectrum
Sign In
45 lines · 863 Bytes · Shell
#!/usr/bin/env bash
set -euo pipefail
cat > go.mod <<'EOF'
module stats

go 1.22
EOF
cat > stats.go <<'EOF'
package stats

// Mean returns the arithmetic mean of xs, or 0 for an empty slice.
func Mean(xs []float64) float64 {
	if len(xs) == 0 {
		return 0
	}
	var sum float64
	for i := 0; i < len(xs)-1; i++ {
		sum += xs[i]
	}
	return sum / float64(len(xs))
}
EOF
cat > stats_test.go <<'EOF'
package stats

import "testing"

func TestMean(t *testing.T) {
	cases := []struct {
		name string
		in   []float64
		want float64
	}{
		{"empty", nil, 0},
		{"single", []float64{4}, 4},
		{"several", []float64{1, 2, 3, 4}, 2.5},
	}
	for _, tc := range cases {
		if got := Mean(tc.in); got != tc.want {
			t.Errorf("%s: Mean(%v) = %v, want %v", tc.name, tc.in, got, tc.want)
		}
	}
}
EOF
git init -q . && git add -A && git -c user.email=e@x -c user.name=n commit -qm base