我目前是程序员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
感谢您使用put CodeEval的建议。我从来没想过这点。与关于比较花车的建议一样。 – jchi2241
发现错误,这是由于浮动精度。谢谢Nick。 – jchi2241