2014-04-19 66 views
1

任何副作用勾股三角所以我有這個天賦,我想解決的(我沒有寫規範)...與等於零

it "returns false if any of the arguments are 0" do 
    # [0, 1, 1].permutation(3) returns all permutations of [0, 1, 1] 
    length = rand(0.01..100.0) 
    [0, length, length].permutation(3).all? { |(a,b,c)| valid_triangle?(a,b,c) }.should be_false 
    end 

這裏是我的代碼

def valid_triangle?(a, b, c) 
#A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2. 
    if a > 0 && b > 0 && c > 0 
    one = a**2 
    two = b**2 
    three = c**2 
    if one+two=three 
     return "true" 
    else 
     return "false" 
    end 
    else 
    return "false" 
    end 
end 

我怎樣才能通過我的規範?我錯過了什麼?

+0

這可能與浮點不精確有關。在乘法之前嘗試將參數轉換爲'BigDecimal'。 – Matt

+0

你應該重新命名你的方法'valid_right_triangle?',或者更好,只是'right_triangle?'。順便說一句,我很好奇:什麼是從你的眼角? –

回答

2

您正在返回"false""true"代替falsetrue,你也檢查one+two=three,當你應該檢查one+two==three(等號檢查,而不是分配)

def valid_triangle?(a, b, c) 
#A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2. 
    if a > 0 && b > 0 && c > 0 
    one = a**2 
    two = b**2 
    three = c**2 
    if one+two == three 
     return true 
    else 
     return false 
    end 
    else 
    return false 
    end 
end 
3

的主要問題是,當測試會對a,bc的值進行置換,但您的方法並不總是檢查它是否等於其他兩邊的平方和的斜邊的平方。例如,如果a=3,b=4c=5,您的測試之一將是4*4 + 5*5 == 3*3。在檢查平方和之前,您需要對a,bc進行排序,無論如何,這是一個好主意,因爲參數之間的斜邊位置不能保證。你也可以簡化你的代碼。這裏是你可以把它寫一個方法:

TOLERANCE = 0.01 

def right_triangle?(a, b, c) 
    return false if a == 0 || b == 0 || c == 0 
    a, b, c = [a,b,c].sort 
    (a**2 + b**2 - c**2).abs < TOLERANCE 
end 

length = rand(0.01..100.0) 
[0.0, length, length].permutation(3).all? { |(a,b,c)| right_triangle?(a,b,c)} 
    #=> false 

[3,4,5].permutation(3).all? { |(a,b,c)| right_triangle?(a,b,c) } 
    #=> true 

因爲你面對的花車,你是否相等比較值時,需要建立寬容一些的水平。爲了演示目的,我使用了任意的固定金額(0.01)。