Tuesday, February 4, 2014

Ruby Puzzles Part Two of n

Basic array manipulation in Ruby cont...


Start with an array of integers 1 through 5.Square each number in the array, then return the sum of all the squared numbers.




        To accomplish this I've written a small function called "squared_sum", which takes an array as an argument. The first step in the method is to set up a sum variable and set it to zero. This will act as a container for our summed numbers. Next we iterate over the array with the .each method to create a loop. For each number(num) we square that number with **2 and assign that to a variable. For each pass in the loop we add the sq_num value to the sum variable with +=. Once we have passed over every number in the array we print out the value of sum. At the very end of the code sample above (outside the method), we are simply creating the array by calling the .to_a method on a range, and then calling our squared_sum method and passing in the array we just created.

    Print out all prime numbers between 1 and n . 




         This one is a little more involved, so please hang in there. My strategy here is to create two methods. One that simply takes in a number and returns true if the number is prime. The second method passes each number of an array into the first method and then adds that number to a list of primes if true is returned. The primes list is then printed. Viola! 
        First is_prime. This method takes a number and then creates a range of number between 2 and the square root of that number. It then takes our number and using the modulo(%) determines if any of the numbers in the newly created range can be evenly divided into our number. If so our number is not a prime, and the method returns false. Otherwise it is a prime and returns true.
        Now check_array_primes. We pass in our array of numbers. The first step creates and empty array of primes. We will push any number that returns with true from the is_prime method into this array. Next we use the .each method to create a loop and iterate each number in the array. Each number is passed to the is_prime method. If that return true, it is added to our list of arrays, otherwise nothing is done.  
       Take a look at this second method. How can it be refactored? Its a pretty easy fix.

    No comments:

    Post a Comment