#soal 1

library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.5.3
library(reshape2)
## Warning: package 'reshape2' was built under R version 4.5.3
data <- datasets::mtcars
data_mtcars <- data[, c("mpg", "disp", "hp", "wt", "qsec")]

#matriks korelasi
cor_mtcars <- cor(data_mtcars)
cor_mtcars
##             mpg       disp         hp         wt       qsec
## mpg   1.0000000 -0.8475514 -0.7761684 -0.8676594  0.4186840
## disp -0.8475514  1.0000000  0.7909486  0.8879799 -0.4336979
## hp   -0.7761684  0.7909486  1.0000000  0.6587479 -0.7082234
## wt   -0.8676594  0.8879799  0.6587479  1.0000000 -0.1747159
## qsec  0.4186840 -0.4336979 -0.7082234 -0.1747159  1.0000000
#heatmap
data_cor <- melt(cor_mtcars)
ggplot(data_cor, aes(Var1, Var2,fill = value)) +
  geom_tile(color = "black") + geom_text(aes(label = round(value, 2)), color = "black") + scale_fill_gradient2(low = "skyblue",high = "pink", mid = "yellow", midpoint = 0, limit = c(-1, 1), name = "Korelasi") +
  theme_minimal() + labs(title = "Heatmap Dataset mtcars", x = "Variabel 1", y = "Variabel 2") + theme(plot.title = element_text(hjust = 0.5))

#soal 2

bern <- function(x,p){p^x*(1-p)^(1-x)}
bern (1,3/6)
## [1] 0.5
#soal 3

cmfbinom <- function(k, n, p) {
  #validasi input
  if (k < 0 || n < 0 || p < 0 || p > 1) {
    stop("Input Tidak Valid")
  }
  #inisialisasi CMF
  cmf <- 0
  #menghitung CMF
  for ( x in 0:k) {
    prob <- choose(n, x)*(p^x)*((1-p)^(n-x))
    cmf <- cmf + prob
  }
  return (cmf)
}

#peluang paling sedikit 2 orang sembuh = 1-p(x < 1)
Peluang = 1 - cmfbinom(1, 12, 0.2)
Peluang
## [1] 0.7251221
#soal 4

cmfpois <- function(x, lamda) {
  if (lamda <= 0) {
    stop("Lamda Harus Bernilai > 0")
  }
  if (x <0) {
    return(0)
  }
  cmf <- 0
  for(k in 0:x) {
    cmf <- cmf + (exp(-lamda) * (lamda^k) / factorial(k))
  }
  return(cmf)
}
Peluang2 <- cmfpois(10, 2) - cmfpois(0, 2)
Peluang2
## [1] 0.8646564
#soal 5

geo <- function (x, p){p*(1-p)^(x-1)}
geo(5, 0.3)
## [1] 0.07203
#soal 6

hyper <- function(x, N, n, k) {(((factorial(k)/(factorial(k - x)*factorial(x)))*(factorial(N-k)/((factorial((N-k) - (n-x)))*(factorial(n-x))))))/(factorial(N)/(factorial(N-n)*factorial(n)))}
hyper(2, 100, 10, 5)
## [1] 0.07021881