Home > Software engineering >  Two Random Numbers Without Repeating
Two Random Numbers Without Repeating

Time:10-25

I'm looking to make a set of two random numbers (e.g., [1,2], [3,12]) with the first number between 1-12, and the second between 1-4. I know how to sample the two numbers independently using:

sample(1:12, 1, replace = T)
sample(1:4, 1, replace = T)

but don't know how to create a system to determine if the pairing of the two numbers has already been rolled, and if so, roll again. Any tips!?

Thanks :)

CodePudding user response:

While this doesn't scale happily (in case you need large-scale simulation), you can do this:

set.seed(42)
di2 <- sample(setdiff(1:4, di1 <- sample(1:12, size = 1)), size = 1)
c(di1, di2)
# [1] 1 2
  • The inner (di1) assignment takes the first from 1:12, so far so good.
  • We then set-diff 1:4 from this so that the second sampling only has candidates that are not equal to di1;
  • The outer (di2) assignment samples from 1:4 without di1 if it was within 1-4.

While not an authoritative proof of correctness,

rand <- replicate(100000, local({ di2 <- sample(setdiff(1:4, di1 <- sample(1:12, size=1)), size = 1); c(di1, di2); }))
dim(rand)
# [1]      2 100000
any(rand[1,] == rand[2,])
# [1] FALSE

CodePudding user response:

Are you looking for sth like:

library(tidyverse)
expand.grid(1:12,1:4) %>%
  as.data.frame() %>%
  slice_sample (n = 5, replace = FALSE)
  • Related