Project Euler: F# to R


As part of getting up to speed, I reworked some basic code I created for solver Project Euler problems using F# into R:

 
 # Fibonacci series 
 # 
 fibsRec <- function(a, b, max, arr) {  
      if (a + b > max) {  
           arr  
      } else {  
           current = a + b  
           newArr = arr  
           newArr[length(arr)+1] = current  
           fibsRec(b, current, max, newArr)  
      }  
 }  
 startList <- c(1,2)  
 result <- fibsRec(1, 2, 40, startList)  
 print(result)  


 # Project Euler - Problem #1
 #
 # Find a way of finding the sum of all the multiples of 3 or 5 below 1000  
 # if we list all the natural numbers below 10 that are multiples of 3 or 5,   
 # we get 3, 5, 6 and 9. The sum of these multiples is 23.   
 # Find the sum of all the multiples of 3 or 5 below 1000.  
 #
 rm(list = ls())  
 num <- seq(1:999)  
 filteredList <- function(l) {  
      newArr <- c(0)  
      for (i in l) {  
           if (i %% 3 == 0 || i %% 5 == 0) {  
                newArr[length(newArr)+1] <- i  
           }  
      }  
      return(newArr)
 }
   
 #print(filteredList(num))  
 sum(filteredList(num))  


 # Project Euler - Problem #6  
 #  
 # Find the difference between the sum of the squares of the   
 # first one hundred natural numbers and the square of the sum.  
 #     
 rm(list = ls())  
 square <- function(x) {  
      x * x  
 }  
 nums = c(1:100)  
 squareList <- c(square(nums))  
 sumOfSquares <- sum(squareList)  
 squareOfSum <- square(sum(nums))  
 result <- squareOfSum - sumOfSquares  
 print(result)  

Comments

Popular posts from this blog

Charting Correlation Matrices in R

Developers in New York City by Zip Code

Cultural Dimensions and Coffee Consumption