Archive

Posts Tagged ‘ruby’

Goldbach Conjecture #Ruby

July 27, 2017 Leave a comment

Return the number of ways to write the given n as the sum of two prime numbers.

Example
For n = 20, the output should be
gold(n) = 2.
There are two ways to represent 20 as the sum of two prime numbers:

3 + 17 = 20,
7 + 13 = 20.


require 'prime'
def gold e
    r = 0
    for i in 2..(e/2)
        r += 1 if Prime.prime?(i) && Prime.prime?(e-i)
    end
    r
end

CodeFights MZbot AllianceVsMonster – Ruby

June 7, 2017 Leave a comment
def allianceVersusMonster hp, ad
    mHp = hp[0]
    mAd = ad[0]
    turns = []
    size = hp.size - 1
    (1...ad.size).each do |x|
        turns <= mAd && cHp >= mHp
        timesToDie = ( mHp / cAd.to_f).ceil
        timesIDie = ( cHp / mAd.to_f).ceil
        return size if timesIDie >= timesToDie
        mHp -= (timesIDie - 1) * cAd 
        w[1] = cHp % mAd + 1
    end
    
    #fight until dead
    turns.each do |w|
        cAd, cHp = w
        return size if cAd >= mAd && cHp >= mHp       
        while cHp > 0 && mHp > 0
            mHp -= cAd
            return size if mHp <= 0
            cHp -= mAd
        end
        size -= 1
    end
    0
end