Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Random Numbers Without Repeating

Tags:

random

r

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 :)

like image 475
wcbrown Avatar asked May 16 '26 14:05

wcbrown


2 Answers

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
like image 70
r2evans Avatar answered May 19 '26 04:05

r2evans


Are you looking for sth like:

library(tidyverse)
expand.grid(1:12,1:4) %>%
  as.data.frame() %>%
  slice_sample (n = 5, replace = FALSE)
like image 38
deschen Avatar answered May 19 '26 05:05

deschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!