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