06/08/2009

Nerd, Jocks ans Lockers

I am a fanatic reader of the Daily WTF but until now I had never taken the time to try and solve a problem from the programming praxis category. So this time, I have gone and done it for the Nerds, Jocks and locker problem. the following is my entry done trying to follow TDD. test_locker_solver.rb:
require 'test/unit'
require 'locker_challenge'

class TestLockerSolver < Test::Unit::TestCase
 def test_prime_set_number_de_1_est_1_1() 
  solver=LockerSolver.new
  assert_equal [1,1], solver.get_prime_set(1)
 end
 def test_prime_set_number_de_2_est_1_2() 
  solver=LockerSolver.new
  assert_equal [1,2], solver.get_prime_set(2)
 end
 def test_prime_set_number_de_3_est_1_3() 
  solver=LockerSolver.new
  assert_equal [1,3], solver.get_prime_set(3)
 end
 def test_prime_set_number_de_4_est_1_2_2() 
  solver=LockerSolver.new
  assert_equal [1,2,2], solver.get_prime_set(4)
 end

 def test_get_open_lockers_1_est_1
  solver=LockerSolver.new
  assert_equal [1], solver.get_open_lockers(1)
 end
 
  def test_get_open_lockers_4_est_1_et_4
  solver=LockerSolver.new
  assert_equal [1,4], solver.get_open_lockers(4)
 end
 
 def test_count_primes_1_est_1x2
   solver=LockerSolver.new
   
   assert_equal({1 => 2}, solver.count_primes(1))
 end
  def test_count_primes_4_est_1x1_2x2
   solver=LockerSolver.new   
   assert_equal({1 => 1, 2=>2}, solver.count_primes(4))
 end
end
and locker_solver.rb:
class LockerSolver
 def get_prime_set(n=1)
  i=2
  while n%i!=0 and i<=n  
   i=i+1
  end
  i>=n ? [1,n] : [i,get_prime_set(n/i)].flatten.sort  
 end
 
 def count_primes(n=1)
  pset=get_prime_set(n)
  map=pset.inject({}) { |memo,n| memo[n].nil? ? memo[n]=1 : memo[n]+=1; memo }
 
 end
 
 def get_open_lockers(n)
  r=[]
  (1..n).each do |l|
    h=count_primes(l).delete_if {|key, value| key<2}
    isOpen=true
    h.each do |prime,count|
      isOpen &= (count%2==0)
    end
    isOpen ? r << l : false
  end
  r
 end
end

Aucun commentaire: