본문 바로가기

스파르타코딩클럽(내일배움캠프)

스파르타코딩클럽 내일배움캠프 6주차3일

728x90

[강의]

강의가 많이 어렵다 열심히 해봐야겠다...

 

 

[알고리즘]

class Solution {
    
        public static int[] solution(String[] keyinput, int[] board) {
            int [] dy = {0,0,-1,1};
            int [] dx = {1,-1,0,0};
            // up 0 down 1 left 2 right 3

            int cy =board[0]/2;
            int cx =board[1]/2;
            int ny =0;
            int nx =0;
            for(int i=0;i<keyinput.length;i++)
            {

                if(keyinput[i].equals("left"))
                {
                    ny= cy + dy[2];
                    nx= cx + dx[2];
                    if(ny>=0 && nx>=0 && nx<board[1] && ny<board[0])
                    {
                        cy = ny;
                        cx = nx;
                    }
                }
                else if(keyinput[i].equals("right"))
                {
                    ny= cy + dy[3];
                    nx= cx + dx[3];
                    if(ny>=0 && nx>=0 && nx<board[1] && ny<board[0])
                    {
                        cy = ny;
                        cx = nx;
                    }
                }
                else if(keyinput[i].equals("up"))
                {
                    ny= cy + dy[0];
                    nx= cx + dx[0];
                    if(ny>=0 && nx>=0 && nx<board[1] && ny<board[0])
                    {
                        cy = ny;
                        cx = nx;
                    }
                }
                else if(keyinput[i].equals("down"))
                {
                    ny= cy + dy[1];
                    nx= cx + dx[1];
                    if(ny>=0 && nx>=0 && nx<board[1] && ny<board[0])
                    {
                        cy = ny;
                        cx = nx;
                    }
                }
            }

            int[] answer = new int[2];
            answer[0] = cy - board[0]/2;
            answer[1] = cx - board[1]/2;
            return answer;
        }
}

 

오답체크 : ny nx 조건문을 || 로자꾸 실수 하는것 같다... &&을 붙여주자...

 

베스트 코드... 3항연산자를 이용해서 해결했다. (프로그래머스 출처)

class Solution {
    public int[] solution(String[] keyinput, int[] board) {
        int[] now = {0, 0};
        for (int i = 0; i < keyinput.length; i++){
            if(keyinput[i].equals("left")) now[0] -= now[0]>-(board[0]/2)?1:0;
            else if(keyinput[i].equals("right")) now[0] += now[0]<(board[0]/2)?1:0;
            else if(keyinput[i].equals("down")) now[1] -= now[1]>-(board[1]/2)?1:0;
            else if(keyinput[i].equals("up")) now[1] += now[1]<(board[1]/2)?1:0;
            }
        return now;
    }
}

푸는 방법은 알고있었으나 익숙하지 않으니 사용하지 않았다. 다음부터는 사용해서 빠르고 간결한 코드로 작성해야겠다.

728x90