How to generate a sequence that increases alternately

I would like to create a sequence starting with 2 and ending with 65, which increases first by 3, then by 1, then by 3, then by 1, etc., giving the final result, which 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 make such a sequence?

+5
source share
5 answers

Easy to generalize

 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 
+4
source

Using recirculation in R, first create all numbers between 3 and 65, and then just select alternative pairs! and after that attach 2 to it.

To select alternative pairs, I select the following pattern: c (FALSE, FALSE, TRUE, TRUE), so the first 2 are rejected, and the next 2 are accepted. E.g. c (3,4,5,6) [c (FALSE, FALSE, TRUE, TRUE)] means 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 am working on Rcpp, I thought that you just need to learn this. Thanks for this question. Completed my first job 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 
+6
source

Perhaps not generalized, but

 > sort(c(seq(2,65,4), seq(5,65,4))) [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 
+3
source

I provide you with the logic to implement it in the programming language that you use.

 #include <iostream> using namespace std; int main() { int start = 2, end = 65; std::cout << start; cout<<"\n"; for(int i=start;i<=end;i++){ if(i == start){ cout<<i+3; cout<<"\n"; i +=3; }else{ cout<<i; cout<<"\n"; } } return 0; } 

Implemented in C ++;

+1
source

Try this to get the first n members of the sequence, we have

enter image description here

 n <- 32 # get first 32 terms x <- 1:n 2+as.integer(x/2)*3+as.integer((x-1)/2) # [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 
+1
source

Source: https://habr.com/ru/post/1259947/


All Articles