tosscoin <- function(n) {
  df <- expand.grid(replicate(n, c("H", "T"), simplify = FALSE),
              KEEP.OUT.ATTRS = FALSE,
              stringsAsFactors = FALSE)
  
  names(df) <- paste0("X", seq_len(n))
  return(df)
}
tosscoin(3)
##   X1 X2 X3
## 1  H  H  H
## 2  T  H  H
## 3  H  T  H
## 4  T  T  H
## 5  H  H  T
## 6  T  H  T
## 7  H  T  T
## 8  T  T  T
urnsamples <- function(x, size, ordered = TRUE, replace = FALSE) {
  if (ordered) {
    # Producto cartesiano
    expand.grid(replicate(size, x, simplify = FALSE),
                KEEP.OUT.ATTRS = FALSE)
  } else {
    # Combinaciones sin orden
    combn(x, size, simplify = FALSE) |>
      do.call(what = rbind)
  }
}
nsamp <- function(n, k, replace = FALSE, ordered = TRUE) {
  if (ordered) {
    if (replace) {
      return(n^k)  # Producto cartesiano con repetición
    } else {
      return(factorial(n) / factorial(n - k))  # Permutaciones sin repetición
    }
  } else {
    if (replace) {
      return(choose(n + k - 1, k))  # Combinaciones con repetición
    } else {
      return(choose(n, k))  # Combinaciones sin repetición
    }
  }
}
library(knitr)
## Warning: package 'knitr' was built under R version 4.4.3
library(kableExtra)
## Warning: package 'kableExtra' was built under R version 4.4.3
# A) Espacio muestral: todas las combinaciones de tirar 3 dados
Omega <- expand.grid(d1 = 1:6, d2 = 1:6, d3 = 1:6)

# B) Evento: casos donde aparecen los valores 2 y 1 (ordenados)
# Queremos los casos donde estén ambos números 1 y 2, y el orden importa
isin_ordered <- function(row, values) {
  any(row == values[1]) && any(row == values[2]) &&
    which(row == values[1])[1] < which(row == values[2])[1]
}

A <- Omega[apply(Omega, 1, isin_ordered, values = c(2, 1)), ]

# C) Tamaño del espacio muestral
w <- nrow(Omega)

# D) Tamaño de la muestra (número de dados)
n <- ncol(Omega)

# E) Dimensiones del espacio muestral
di <- dim(Omega)

# F) Tamaño del evento
a <- nrow(A)

# Mostrar tabla con formato
kable(A, align = "ccc", col.names = c("Dado 1", "Dado 2", "Dado 3")) %>%
 kable_styling() %>%
  kable_classic_2(full_width = FALSE)
Dado 1 Dado 2 Dado 3
2 2 1 1
8 2 2 1
9 3 2 1
10 4 2 1
11 5 2 1
12 6 2 1
14 2 3 1
20 2 4 1
26 2 5 1
32 2 6 1
38 2 1 2
74 2 1 3
110 2 1 4
146 2 1 5
182 2 1 6
A
##     d1 d2 d3
## 2    2  1  1
## 8    2  2  1
## 9    3  2  1
## 10   4  2  1
## 11   5  2  1
## 12   6  2  1
## 14   2  3  1
## 20   2  4  1
## 26   2  5  1
## 32   2  6  1
## 38   2  1  2
## 74   2  1  3
## 110  2  1  4
## 146  2  1  5
## 182  2  1  6