Today I solved this algorithm that is the third problem in Project Euler.
This still need some improvement, because even when the last prime number is found it still counts and takes a really long time when given big numbers.
result = 0
(2...num).each do |i|
result = i if (num % i) == 0 && i.prime?
I will update this code as soon as I find a better solution but for now it works.
Why are solving algorithms Adnilson, shouldn’t you work on building applications? Yes, you are right! The thing with algorithms is that it helps you solve problems and are good to make your mind look for solutions. This way you build a blueprint and whenever you get a problem you tackle the problem instead of being tackled by it.
In Ruby things sometimes are too easy and today I will go back to school and review the bubble sort, this algorithm is not the most efficient way of sorting but is a simple and cool exercise.
In Ruby if you want to sort say, an array you can do it by doing array.sort and bam! There it is.
length = array.length - 1
swapped = false
(0...length).each do |i|
if array[i] > array[i+1]
array[i], array[i+1] = array[i+1], array[i]
swapped = true
break if !swapped
I guess the code speaks for itself. In a lower level language the program would have an extra variable to store the value of one of the array contents in order to swap.
The first time I did this was in Pascal, then Fortran in college.
Today I encountered an algorithm to solve and the amazing Ruby syntax made me solve this problem with a succinct code with testing included.
All words in the title should be capitalised except a few ones like “a”, “the”, “to”, “at”, “in”, “with”, “and”, “but” and “or”.
To make this very short the solution is here:
class MyTest &lt; Test::Unit::TestCase
test &quot;capitalization&quot; do
assert_equal title_case("i love solving problems and it is fun!"),
("I Love Solving Problems and It Is Fun!")
assert_equal title_case("wHy DoeS A biRd Fly?"),
("Why Does a Bird Fly?")
lower_list = %w(a the to at in with and but or)
words = title.downcase.split
words.each do |word|
word.capitalize! unless lower_list.include?(word)
title = words.join(' ')