我目前是一名程序员菜鸟,我一直在解决 CodeEval 上的问题以进行练习。现在,我正在处理 CodeEval 的“寻找正方形”问题。https://www.codeeval.com/open_challenges/101/
我使用的方法是 Joel Brown 描述的方法:https ://softwareengineering.stackexchange.com/questions/176938/how-to-check-if-4-points-form-a-square
我通过了给出的 10 个测试用例中的 9 个。问题是尽管 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