Best way to deal with floating numbers: don't

Here is the problem: https://leetcode.com/problems/valid-boomerang/

boomerang is a set of 3 points that are all distinct and not in a straight line.
Given a list of three points in the plane, return whether these points are a boomerang.

Example 1:
Input: [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: [[1,1],[2,2],[3,3]]
Output: false

Note:
  1. points.length == 3
  2. points[i].length == 2
  3. 0 <= points[i][j] <= 100
Although this is a super easy problem, there is one learning here: whenever you think about having float numbers in your code, try to avoid them. You'll get bogged down into rounding problems left and right. Just do your calculations on a paper, remove the divisions, and end up with a simple integer equation. Also, go up a notch in terms of the data type that you're using in order to avoid overflow, hence if the input is "int", work with "long". As simple as that. Code's below, many cheers, ACC.


public class Solution
{
    public bool IsBoomerang(int[][] points)
    {
        long x1 = points[0][0];
        long y1 = points[0][1];
        long x2 = points[1][0];
        long y2 = points[1][1];
        long x3 = points[2][0];
        long y3 = points[2][1];

        if ((x1 == x2 && y1 == y2) ||
            (x1 == x3 && y1 == y3) ||
            (x2 == x3 && y2 == y3))
        {
            return false;
        }
        else if (x2 == x1)
        {
            return x3 != x1;
        }
        else
        {
            return (x2 - x1) * y3 != x3 * (y2 - y1) + (x2 - x1) * y1 - x1 * (y2 - y1);
        }
    }
}

Comments

Popular posts from this blog

Changing the root of a binary tree

Prompt Engineering and LeetCode

ProjectEuler Problem 719 (some hints, but no spoilers)