Casper
Casper

Reputation: 21

Get a seed to generate a specific set of pseudo-casual number

I was wondering if there is a way in R to find the specific seed that generates a specific set of numbers;

For example:

sample(1:300, 10)

I want to find the seed that gives me, as the output of the previous code:

58 235 243  42 281 137   2 219 284 184

Upvotes: 2

Views: 192

Answers (1)

SamR
SamR

Reputation: 20385

As far as I know there is no elegant way to do this, but you could brute force it:

desired_output <- c(58, 235, 243, 42, 281, 137, 2, 219, 284, 184)
MAX_SEED <- .Machine$integer.max
MIN_SEED <- MAX_SEED * -1
i  <- MIN_SEED
while (i < MAX_SEED - 1) {
    set.seed(i)
    actual_output <- sample(1:300, 10)
    if (identical(actual_output, desired_output)) {
        message("Seed found! Seed is: ", i)
        break
    }
    i  <- i + 1
}

This takes 11.5 seconds to run with the first 1e6 seeds on my laptop - so if you're unlucky then it would take about 7 hours to run. Also, this is exactly the kind of task you could run in parallel in separate threads to cut the time down quite a bit.

EDIT: Updated to include negative seeds which I had not considered. So in fact it could take twice as long.

Upvotes: 4

Related Questions