Help in coding a program


#1

how to write a code which displays

1 2 2 3 3 3 1 2 2 3 3 3 1 2 2 3 3 3


#2

Hi there,

Since you're asking in terms of programming, I would suggest something along the lines of:

my_max = 3
my_vec = c()
for( i in seq(1, my_max) ){
  my_vec = append(my_vec, rep(i, i))
}
my_vec = rep(my_vec, my_max)
cat(my_vec, "\n")
print(my_vec)

Which will yield:

1 2 2 3 3 3 1 2 2 3 3 3 1 2 2 3 3 3 
 [1] 1 2 2 3 3 3 1 2 2 3 3 3 1 2 2 3 3 3

But, please note, that if this is homework, then to be frank, you may have a solution to your problem, but you have learned nothing. Learning to program is not just writing/obtaining the code, which solves the problem, but very much also learning to think "programmatically" :slightly_smiling_face:


#3

In terms of a function, something like that would do the job:

##' function for expanding a vector
##'
##' This function expands a given vector v. It expands each value acording to the matching value    on the vector e, and then replicate the output accordingly with t
##' @title myFun
##' @param v numeric vector containing the original values to be expanded
##' @param e numeric vector containing how much times to expand each member of vector v
##' @param t how many replicates we want numeric vector of length 1.
##' @return a vector
##' @author Fernando Arce
myFun <- function(v,e,t){
             rep(rep(v,e),t)
}

You can call it directly with the desired numbers, of course

> myFun(1:3,1:3,3)
 [1] 1 2 2 3 3 3 1 2 2 3 3 3 1 2 2 3 3 3

#4

Clearly the easiest answer is: cat("1 2 2 3 3 3 1 2 2 3 3 3 1 2 2 3 3 3")