ruby - Determining if 4 given integer points creates a square -
i'm programmer noob, , i've been working through problems on codeeval practice. right now, i'm working on codeeval's "find square" problem. https://www.codeeval.com/open_challenges/101/
the method i'm utilizing 1 described joel brown: https://softwareengineering.stackexchange.com/questions/176938/how-to-check-if-4-points-form-a-square
i'm passing 9 out of 10 test cases given. thing though codeeval doesn't seem give test inputs, i'm working blind on figuring out case i'm missing. i'm assuming case that's suppose test "true" leaking through else statement, meaning i'm missing 1 of possible point assignment positions given points.
def is_square? a, b, c, d #distances between 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 sides 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 sides 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 sides equal else return false end return true end file.open(argv[0]).each_line |line| a, b, c, d = line.strip.split(" ") = 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
it looks can puts
statements in codeeval system, add debugging prints code, let extract test input , let debug locally.
also, you're comparing floating point values using ==
, !=
. lead issues. 2 edges may calculated be, example, 4.000001
, 4.0
. these not equal, in fact are, , falling victim representation being imprecise.
usually, comparisons of floating point values use acceptable difference between numbers consider them equal. here question regarding ruby code.
good luck!
Comments
Post a Comment