# HW 1 problem 5 -- count DNA sequences # # deduct(m, letters) returns the number of sequences that # can be built from a collection of letters # # m = length of the sequence; must be at most sum(letters) # # letters = array of numbers telling how many of each letter # # Solve the homework problem by cutting and pasting this code into # an R console window, then issuing commands # # > letters <- c(4,4,4,3) # > deduct(3,letters) # > deduct(6,letters) # > deduct(9,letters) # > deduct(12,letters) # # (Be prepared to wait a while for the last command.) deduct <- function (m, letters) { count <- 0 if(m>0) { # ...then build another level of the decision tree for (k in 1:length(letters)) { if(letters[k] > 0) { # prepare to reduce the number of the kth letter by one: deduction <- array(0, length(letters)) deduction[k] <- 1; # count the number of leaves in the letter k subtree: count <- count + deduct(m-1, letters-deduction) } } } else { # ...otherwise we are at a leaf, so just count this leaf count <- 1 } return(count) }