3 comments on “Honing Your R Skills for Job Interviews

  1. I was thinking about a more intuitive solution in order to generate n uniformly distributed values in range 1..7 starting from the rand5 function (which returns n uniformly distributed values in 1..5):

    rand7b() :
    . generate 7n uniformly distributed values in 1..35
    . uniformly pick n values of the 7n
    . translate 1..35 into 1..7 with x%%5 +1

    Here is my code (sorry for not managing the highlighting):

    ## Returns n random integers in the range 1..5.
    rand5 <- function(n=1) sample(1:5, n, replace=TRUE)

    ## Returns n random integers in the range 1..7.
    ## FAIL !!
    rand7a <- function(n=1) {
    round(rand5(n) * 7 / 5)
    }

    ## Returns n random integers in range 1..7
    rand7b <- function(n=1) {
    ## x will have 7*n uniformly distributed values in range 1..35
    x <- c()
    for (i in 0:6)
    x <- c(x, i*5 + rand5(n))

    ## Uniformly pick n elements in range 1..35
    ## Just for fun, from each group of 7 elements, pick 1 of the first 5 :)
    # i <- 0:(n-1) * 7 + rand5(n)
    ## ... or just do it quickly
    i <- 0:(n-1) * 7

    ## Translate 1..35 into 1..7
    x[i] %% 7 + 1
    }

    ## Adam Rosenfield's solution.
    ## Good, but slower then rand7b.
    rand7c1 <- function(dummy=1) {
    x 21) x <- rand5() + (rand5() - 1) * 5
    return (x %% 7 + 1)
    }
    rand7c <- function(n=1) {
    sapply(1:n, FUN=rand7c1)
    }

    ## Pick the function to use.
    rand7 <- rand7b

    ## Generate (large) samples.
    x5 <- rand5(35000)
    x7b <- rand7b(35000)
    x7c <- rand7c(35000)

    ## Print the "histogram".
    print(table(x5))
    print(table(x7b))
    print(table(x7c))

  2. In the first problem you can avoid the warnings as follows:

    m <- 1:100
    is.mod.3 <- m%%3 == 0
    is.mod.5 <- m%%5 == 0
    m[is.mod.3] <- "fizz"
    m[is.mod.5] <- "buzz"
    m[is.mod.3 & is.mod.5] <- "fizzbuzz"
    print(m)

  3. Another way to avoid the warnings with fizzbuzz:

    n <- 1:100
    m <- n
    m[n%%3==0] <- "fizz"
    m[n%%5==0] <- "buzz"
    m[(n%%5==0)&(n%%3==0)] <- "fizzbuzz"
    print(m)

Leave a Reply

Your email address will not be published. Required fields are marked *


four + two =

* Copy This Password *

* Type Or Paste Password Here *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>