luke123
luke123

Reputation: 641

Creating a vector of numbers where no number is within 2 of the previous element

I want to create a vector of numbers which are randomly spaced between 6-20, 21-35 etc all the way to 500. I have done this with sapply

positions <- sapply(seq(6, 500, by = 15),function(x) x + sample(1:15, 1)) 

I want to add one more rule to this sequence. I don't want any numbers in this vector to be within 2 of each other, i.e. if my first number is 20 I don't want 21 or 22 for my second number and so on. How could I accomplish this?

Upvotes: 1

Views: 71

Answers (2)

Nishanth
Nishanth

Reputation: 7130

This obfuscated code does it - let me see if I can clean it up.

positions <- c()
x <- 0
for (i in seq(6, 500, 15))
{
    sub.samples <- setdiff(1:15 + i, seq(x-2,x+2,1))
    x <- sample(sub.samples, 1)
    positions <- c(positions,x)
}

Upvotes: 1

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

It sounds like you don't care about the length of the sequence. If that is the case, and if I understand your question correctly, something like the following should do what you want:

positions <- positions[diff(positions) > 2]

You may need to use a while statement too, in case after removing some values, there are still values within the threshold for removal.

Upvotes: 2

Related Questions