simulate_card_draw <- function() {
# Create a deck of 52 cards with values
# deck <- c(rep(2:10, 4), rep(11, 4), rep(12, 4), rep(13, 4), rep(1, 4))
deck <- rep(1:13, 4)
# Draw 3 cards randomly from the deck
drawn_cards <- sample(deck, 3, replace = FALSE)
# Find the card with the lowest value
# min_card <- min(drawn_cards)
# Create a table of card counts to ensure only the drawn cards are removed
deck_table <- table(deck)
# Remove the drawn cards (decrease the count of each drawn card)
for (card in drawn_cards) {
deck_table[as.character(card)] <- deck_table[as.character(card)] - 1
}
# Create a new deck from the remaining cards (expand the table back into a vector)
remaining_deck <- as.integer(rep(names(deck_table), deck_table))
# Identify the position of the first occurrence of the min card in drawn cards
min_card_index <- which.min(drawn_cards)
# Draw a new card to replace the lowest card
new_card <- sample(remaining_deck, 1)
# Replace the first occurrence of the lowest card with the new card
drawn_cards[min_card_index] <- new_card
# Return the sum of the values of the 3 cards
sum(drawn_cards)
}
# Run the simulation
simulate_card_draw()
## [1] 22
#######################################################
set.seed(123)
simulations <- replicate(10^5, simulate_card_draw())
mean(simulations)
## [1] 24.29939
card_draw_A <- function() {
deck <- rep(1:13, 4)
drawn_cards <- sample(deck, 3, replace = FALSE)
new_deck <- deck
for(cards in drawn_cards){
index <- which(cards == new_deck)[1]
new_deck <- new_deck[-index]
}
min_card_index <- which.min(drawn_cards)
new_card <- sample(new_deck, 1)
drawn_cards[min_card_index] <- new_card
sum(drawn_cards)
}
simulations_A <- replicate(10^5, card_draw_A())
mean(simulations_A)
## [1] 24.2906
card_draw_B <- function() {
deck <- rep(1:13, 4)
drawn_cards <- sample(deck, 4, replace = FALSE)
return(sum(drawn_cards) - min(drawn_cards[1:3]))
}
simulations_B <- replicate(10^5, card_draw_B())
mean(simulations_B)
## [1] 24.27267
library(microbenchmark)
set.seed(12345)
comparison <- microbenchmark(simulate_card_draw(), # povodne
card_draw_A(), # vymyslene na hodine
card_draw_B()) # dostala som po hodine
comparison
## Unit: microseconds
## expr min lq mean median uq max neval
## simulate_card_draw() 99.8 102.05 110.548 103.80 111.15 247.4 100
## card_draw_A() 15.1 16.50 17.774 17.55 18.50 26.1 100
## card_draw_B() 5.6 6.20 6.988 6.70 7.25 16.5 100
boxplot(comparison)
