[Easy] 1232. Check If It Is a Straight Line

문제

You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

예시

Example 1:

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false

 

제약 조건

Constraints:

  • 2 <= coordinates.length <= 1000
  • coordinates[i].length == 2
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • coordinates contains no duplicate point.

 

해결 과정

  • x축, y축과 평행인지 확인할 때 사용할 변수들을 선언한다. 
  • for문을 돌며 coordinates를 완전 탐색한다. 초기값을 index 0으로 지정해주었으니 1부터 탐색한다.
    • pointX가 coordinates[i][0]과 같으면 countX를 증가시킨다.
    • 만약 countX가 length - 1이라면 모든 x의 값이 같기 때문에 x축과 평행한 것이다. 그러므로 true를 반환한다.
    • Y도 위의 로직과 동일하게 계산한다.
  • 만약 x축, y축과 평행하지 않다면 기울기를 구하여 기울기가 일정한지 확인한다.
  • 기울기를 비교할 x, y 변수를 선언한다. 초기값은 index 1과 0으로 구성한다.
  • coordinates를 순회하며 diffX 와 diffY를 구한다.
  • x / y 와 diifX / diffY가 같지 않다면, 기울기가 일정하지 않은 것이기 때문에 false를 반환한다.
  • 전체 탐색을 마쳤다면 기울기가 일정한 것이기 때문에 true를 반환한다.

 

해결 코드

/**
 * @param {number[][]} coordinates
 * @return {boolean}
 */
var checkStraightLine = function(coordinates) {
    
    // x축, y축과 평행인지 확인
    let pointX = coordinates[0][0], 
        pointY = coordinates[0][1], 
        countX = 0,
        countY = 0;
    
     for(let i = 1 ; i < coordinates.length; i++){
        if(pointX === coordinates[i][0]){
            countX++;
            if(countX === coordinates.length - 1) return true;
        }else if(pointY === coordinates[i][1]){
            countY++;
            if(countY === coordinates.length - 1) return true;
        }else{
            break;
        }        
    }
    
    // 기울기가 일정한지 확인
    let x = coordinates[1][0] - coordinates[0][0],
        y = coordinates[1][1] - coordinates[0][1];
   
    for(let i = 1 ; i < coordinates.length - 1; i++){
        let diffX = coordinates[i + 1][0] - coordinates[i][0];
        let diffY = coordinates[i + 1][1] - coordinates[i][1];
        console.log(diffX)
        console.log(diffY)

        if(x/y !== diffX/diffY) return false;
    }
    return true;
};