Monthly Archives: December 2011

MuroBBS Programming Challenge 1

It’s been a while since the last post. I started my studies as a statistics major in university and have been doing little with R but mostly just reading other blogs and taking our university’s R course which was just the basics so nothing new there.

I mentioned earlier that the Jets are back and they’re doing pretty nice. Teemu Selänne returned to Winnipeg to play against Jets a while ago and it was awesome night.

This post is about programming “challenge” in a Finnish computer themed forum MuroBBS  (in Finnish) where people write different programming challenges and others write solutions with different languages. I chose R since it’s not so familiar there.

First warm up was to create following sequence given the amount of maximum stars
*
**
***
****
*****
****
***
**
*
My code for that:

# MuroBBS Ohjelmointipähkinä 1
# http://murobbs.plaza.fi/1707865276-post2.html
stars <- function(n) {
sequence <- c(1:n, (n-1):1)
for (i in sequence) {
# Changed from print to cat, thanks for commenting Tal!
cat(rep('*', i), "\n")
}
}

When called, it gives output:

> stars(5)
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*

However, I started thinking that is there a solution which doesn’t require a loop but that uses some of R’s own vector/list handling techniques?

edit
I wanna add Tony Breyal’s solution from comments as it’s pretty much superior to my unefficient for-loop:

stars2 <- function(n) {
myseq <- c(1:n, (n-1):1)
stars <- sapply(myseq, function(i) paste(rep("*", i), collapse = ""))
cat(stars, sep = "\n")
}

 

I’ve read about for-loop being really slow so after testing with Tony’s solution, I did little benchmarking to see that my solution really was terrible:

library(rbenchmark)
benchmark(stars(100), stars2(100), columns= c("test", "elapsed", "relative"))<strong>
</strong>
#       test    elapsed    relative
#1  stars(100)   20.72       26.5641
#2 stars2(100)    0.78       1.0000

So as you can see, mine was over 26 times slower than Tony’s.

More challenges and solutions in later posts.