2016-11-18 49 views
5

我想创建一个从2开始到65结束的序列,它先增加3,然后增加1,然后增加3,然后增加1,依此类推,给出看起来像这样的最终结果:如何生成一个交替递增的序列

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) 

有没有人知道如何去产生这样一个序列?

回答

4

容易普及

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 
+0

不错的做法! –

3

也许不是普及,但

> 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 
+0

好答案 - 但对代码的解释有助于人们理解他们在做什么。一个新手可能不知道'c'的意思,或者'seq'中的所有参数意味着什么。 – Addison

1

我提供你的逻辑实现它在你所使用的编程语言。

#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; 
} 

实现在C++;

+0

做这个逻辑工作?只有当我== 2你递增3其余的时间,它会增加只有1右?我弄错了吗? –

+0

是的,它会工作,因为我不是硬编码值2,而是我正在使用开始比较。是的,它会适用于任何开始结束价值。 @ joel.wilson – PassionInfinite

+0

问题是关于R语言而不是C++ – Uwe

6

在R中使用回收利用,首先创建3 & 65之间的所有数字,并从中选择备用对!然后将2连接到它。要选择替代对,我选择以下模式:c(FALSE,FALSE,TRUE,TRUE),使前2个被拒绝,接下来2个被接受。 例如C(3,4,5,6)[C(FALSE,FALSE,TRUE,TRUE)]表示3,4被拒绝和5,6-接受

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 

由于我的工作在Rcpp上,我认为应该就此进行探索。感谢这个问题。在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 
+0

#joel.wilson先生谢谢你的解决方案非常感谢,请求你可以请你解释c(F,F,T,T)。 –

1

试试这个来获取序列的前n项,我们有

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

R中的数学运算是矢量化的,所以不需要'sapply'。好得多的x <-1:n; 2 + as.integer(x/2)* 3 + as.integer((x-1)/ 2)'。 – nicola

+0

肯定会让它更快 –