2013-10-07 38 views
1

我目前是程序員noob,我一直在努力解決CodeEval上的問題。現在,我正在研究CodeEval的「查找廣場」問題。 https://www.codeeval.com/open_challenges/101/確定4個給定的整數點是否創建了一個正方形

我利用的方法是由Joel布朗描述的一個:https://softwareengineering.stackexchange.com/questions/176938/how-to-check-if-4-points-form-a-square

我傳遞9出來的給定的10測試用例。事情是,雖然CodeEval似乎沒有給你他們的測試輸入,所以我正在弄清楚我錯過了什麼情況。我假設一個假設測試爲「真實」的案例正在泄漏到else語句中,這意味着我缺少給定點的可能點分配位置之一。

def is_square? a, b, c, d 
     #distances between all points 
     ab = Math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2) 
     ac = Math.sqrt((a[0] - c[0])**2 + (a[1] - c[1])**2) 
     ad = Math.sqrt((a[0] - d[0])**2 + (a[1] - d[1])**2) 

     cd = Math.sqrt((c[0] - d[0])**2 + (c[1] - d[1])**2) 
     bc = Math.sqrt((b[0] - c[0])**2 + (b[1] - c[1])**2) 
     bd = Math.sqrt((b[0] - d[0])**2 + (b[1] - d[1])**2) 

     ba = ab, ca = ac, da = ad, dc = cd, cb = bc, db = bd 

     #possible point positions 
     if ab == ac 
     return false if bc != Math.sqrt(ab**2 + ac**2) #check if right triangle 
     return false if bd != cd #check if other sides equal each other 
     return false if bc != ad #check diagonals 
     return false if ab != bd #check if all sides are equal 
     elsif ab == ad 
     return false if bd != Math.sqrt(ab**2 + ad**2) #check if right triangle 
     return false if bc != dC#check if other sides equal each other 
     return false if ac != bd #check diagonals 
     return false if ab != bC#check if all sides are equal 
     elsif ac == ad 
     return false if cd != Math.sqrt(ac**2 + ad**2) #check if right triangle 
     return false if cb != db #check if other sides equal each other 
     return false if ab != cd #check diagonals 
     return false if ac != cb #check if all sides are equal 
     else 
     return false 
     end 

     return true 
    end 

    File.open(ARGV[0]).each_line do |line| 
     a, b, c, d = line.strip.split(" ") 

     a = a.scan(/\d+/).map(&:to_i) 
     b = b.scan(/\d+/).map(&:to_i) 
     c = c.scan(/\d+/).map(&:to_i) 
     d = d.scan(/\d+/).map(&:to_i) 

     puts is_square?(a, b, c, d) 
    end       

回答

1

看起來你可以做的CodeEval系統puts報表,所以加一些調試打印到你的代碼,這將讓你提取測試輸入,讓您調試在本地。

此外,您正在使用==!=比較浮點值。這通常會導致問題。兩條邊可以計算爲例如4.0000014.0。這些不會是平等的,但實際上它們可能是,並且正在成爲不精確的表示的受害者。

通常,浮點值的比較使用數字之間的可接受差異來考慮它們相等。 Here is a question regarding that with Ruby code

祝你好運!

+0

感謝您使用put CodeEval的建議。我從來沒想過這點。與關於比較花車的建議一樣。 – jchi2241

+0

發現錯誤,這是由於浮動精度。謝謝Nick。 – jchi2241

相關問題