[프로그래머스] 캐릭터의 좌표 - JS

Lenny·2023년 7월 3일

문제

풀이

function solution(keyinput, board) {
    
    const horizontalMax = Math.floor(board[0] / 2);
    const verticalMax = Math.floor(board[1] / 2);
  	
    let x = 0;
    let y = 0;
    
    
  	
    for(let k of keyinput){
        switch(k){
            case "left": x--; break;
            case "right": x++; break;
            case "down": y--; break;
            case "up": y++; break;
        }
        
      	
        if(Math.abs(x) > Math.abs(horizontalMax)) {
            x = x > 0 ? horizontalMax : horizontalMax * -1;
         }
        if(Math.abs(y) > Math.abs(verticalMax)) {
            y = y > 0 ? verticalMax : verticalMax * -1;
        }
        
    }
    return [x,y];
}
profile
🧑‍💻

0개의 댓글