Solving Algorithms – Largest prime factor

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.

require 'prime'

def largestPrime(num)
  result = 0
  (2...num).each do |i|
    result = i if (num % i) == 0 && i.prime?
  end
  puts result
end

largestPrime(13195)

I will update this code as soon as I find a better solution but for now it works.

Solving Algorithms – Bubble Sort

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.
The code:

 

length = array.length - 1
loop do
  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
    end
  end
  break if !swapped
end

puts array

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.

Solving Algorithms – Title Capitalisation

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:

require 'test/unit'

class MyTest < Test::Unit::TestCase
  test "capitalization" 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?")
  end
end

def title_case(title)
  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)
  end
  title = words.join(' ')
end