Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a sequence that increments alternately

Tags:

r

I would like to create a sequence starting at 2 and ending at 65, which increments first by 3, then by 1, then by 3, then by 1, and so on, giving an end result that looks like this:

sequence(2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65)

Does anyone know how to go about generating such a sequence?

like image 873
Nabi Shaikh Avatar asked Nov 18 '16 06:11

Nabi Shaikh


2 Answers

Using recycling in R, first create all numbers between 3&65 and from that just selecting alternate pairs! and after that attach the 2 to it.

To select the alternate pairs , i choose the following pattern : c(FALSE,FALSE,TRUE,TRUE) such that first 2 are rejected and next 2 are accepted. For e.g. c(3,4,5,6)[c(FALSE,FALSE,TRUE,TRUE)] means that 3,4 are rejected and 5,6 are accepted

c(2,c(3:65)[c(F,F,T,T)])
[1]  2  5  6  9 10 13 14 17 18 21 22 25 26 29 30 33 34 37 38 41 42 45 46 49 50 53 54 57 58 61 62
[32] 65

Since I'm working on Rcpp, I thought shall just explore on that. Thanks for this question. Completed my first assignment in Rcpp :)

library(Rcpp)

cppFunction('NumericVector func(int start, int end){
        int j = 0;
        int len = ceil((end-start)/2);
        if (end%2 != 0){
          len+=1;
        }
        Rcpp::NumericVector result(len);

        result[j++] = start;

        int i = start;
        while(j <= len){
            if (j%2 == 0){
                result[j++] = i+1;
                i+=1;
            }
            else {
                result[j++] = i+3;
                i+=3;
            }
        }              
        return result;
  }')

> func(2,65)
 [1]  2  5  6  9 10 13 14 17 18 21 22 25 26 29 30 33 34 37 38 41 42 45 46 49 50 53 54 57 58 61 62 65
> func(2,20)
[1]  2  5  6  9 10 13 14 17 18
> func(1,10)
[1] 1 4 5 8
like image 78
joel.wilson Avatar answered Oct 16 '22 18:10

joel.wilson


Easily generalizable

begin = 2
end = 65
d = c(3, 1)
l = length(d)
cumsum(c(begin, rep(d, len = (end-l)/l)))

[1]  2  5  6  9 10 13 14 17 18 21 22 25 26 29 30 33 34 37 38 41 42 45 46 49 50 53 54 57 58 61 62 65
like image 4
ExperimenteR Avatar answered Oct 16 '22 18:10

ExperimenteR