# ----------------------------------------------------------------------
# Programming and Data Analysis with R - Exercises B
# Exercise A
# ----------------------------------------------------------------------

rm(list = ls())

# 1 --------------------------------------------------------------------
var2 <- function(x) {
  mean((x - mean(x))^2)
}

# 2 --------------------------------------------------------------------
var3 <- function(x) {
  n <- length(x) # Get the length of the vector x
  D <- matrix(0, nrow = n, ncol = n) # Creation of an empty matrix
  for (i in 1:n) {
    for (j in 1:n) {
      D[i, j] <- (x[i] - x[j])^2
    }
  }
  sum(D) / (2 * n^2)
}

# 3 --------------------------------------------------------------------
x <- c(1, 4, 2, 2, 10)
c(var2(x), var3(x))

# 4 --------------------------------------------------------------------
x <- 1:3000
var2(x)
var3(x) # Much slower than var2(x)

# 5 --------------------------------------------------------------------
x <- c(1, 4, 2, 2, 10) # The data of point 3
var2(x)
var(x) # Larger: it divides by n - 1 and not by n
var2(x) * 5 / 4 # The same value as var(x), since n = 5
