MuroBBS Programming Challenge 1

December 30, 2011

(This article was first published on Rock 'n' R » R, and kindly contributed to R-bloggers)

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
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?

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:

benchmark(stars(100), stars2(100), columns= c("test", "elapsed", "relative"))<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.

To leave a comment for the author, please follow the link and comment on their blog: Rock 'n' R » R. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)