I am working with the R programming language.

- Suppose there are 10 coins : each coin has 0.5 probability of heads and 0.5 probability of tails
- Each turn, I randomly generate an integer between 0 and 10. I then randomly select those many coins (sampling without replacement)
- I then flip those coins
- I want to repeat this process until at least one head has appeared in all coins

Here is the R code I wrote for this problem (1 = head, 0 = tails, -1 = not selected):

```
multi_coins_flip_until_first_head <- function(n) {
count_coins <- numeric(n)
head_seen_coins <- logical(n)
flips_coins <- vector("list", n)
while(any(!head_seen_coins)) {
selected_coins <- sample(seq_len(n), sample(seq_len(n), 1))
for (i in seq_len(n)) {
if (i %in% selected_coins) {
flip <- sample(c(1, 0), 1)
count_coins[i] <- count_coins[i] + 1
flips_coins[[i]] <- c(flips_coins[[i]], flip)
if (flip == 1) {
head_seen_coins[i] <- TRUE
}
} else {
flips_coins[[i]] <- c(flips_coins[[i]], -1)
}
}
}
return(list("Number of Flips for First Head" = count_coins, "Sequence" = flips_coins))
}
```

When I look at the results of this function:

```
> multi_coins_flip_until_first_head(10)
$`Number of Flips for First Head`
[1] 10 7 5 9 5 8 7 9 5 7
$Sequence
$Sequence[[1]]
[1] 0 -1 -1 1 -1 0 1 0 -1 -1 -1 -1 0 -1 -1 1 -1 0 0 -1 -1 -1 1 -1
$Sequence[[2]]
[1] -1 -1 0 -1 1 -1 0 -1 0 -1 -1 -1 -1 1 -1 -1 -1 -1 0 -1 -1 -1 -1 1
$Sequence[[3]]
[1] -1 -1 -1 -1 -1 0 -1 -1 0 -1 0 -1 -1 -1 0 -1 -1 -1 -1 -1 -1 -1 -1 1
$Sequence[[4]]
[1] 0 1 -1 1 -1 -1 -1 0 -1 -1 0 -1 -1 -1 1 -1 0 1 -1 -1 -1 -1 1 -1
$Sequence[[5]]
[1] -1 -1 1 -1 1 -1 -1 -1 -1 -1 -1 1 -1 -1 -1 -1 0 -1 -1 0 -1 -1 -1 -1
$Sequence[[6]]
[1] -1 -1 -1 -1 -1 -1 -1 -1 -1 0 -1 1 -1 -1 1 0 -1 1 -1 -1 1 1 -1 0
$Sequence[[7]]
[1] -1 0 -1 -1 -1 1 1 0 -1 -1 -1 -1 -1 1 -1 -1 -1 -1 -1 1 1 -1 -1 -1
$Sequence[[8]]
[1] 1 0 1 0 -1 -1 -1 -1 -1 0 -1 -1 -1 -1 -1 1 -1 -1 0 1 -1 0 -1 -1
$Sequence[[9]]
[1] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 0 -1 -1 -1 1 -1 -1 -1 -1 0 -1 -1
$Sequence[[10]]
[1] -1 -1 -1 -1 1 -1 -1 -1 1 1 -1 -1 1 0 -1 -1 -1 -1 -1 -1 0 -1 1 -1
```

It is telling me that the first coin took 10 flips to get the first head - but when I inspect the output `Sequence[[1]]`

, I can see that the first head appeared after the 4th flip.

Can someone please show me how to fix this?