[TIL] 1월 23일 주말학습

yeon·2021년 1월 25일
0

주말 학습

이코테 책 알고리즘 문제 학습

ch4 구현파트

상하좌우(110p)

일련의 명령에 따라서 개체를 차례대로 이동시킴

→ 시뮬레이션 유형

연산 횟수는 이동횟수와 비례

시간 복잡도 O(n)

public class Implementation4_1_1 {
		// 내 풀이 
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int locationX = 1;
        int locationY = 1;
        s.nextLine(); // 버퍼 비우기 
        String moveInput = s.nextLine();
        String[] moveArr = moveInput.split(" ");
        for (int i = 0; i < moveArr.length; i++) {
            if (locationX == n && moveArr[i].equals("R")) continue;
            if (locationY == n && moveArr[i].equals("D")) continue;
            if (locationX == 1 && moveArr[i].equals("L")) continue;
            if (locationY == 1 && moveArr[i].equals("U")) continue;
            switch (moveArr[i]) {
                case "L":
                    locationX--;
                    break;
                case "R":
                    locationX++;
                    break;
                case "U":
                    locationY--;
                    break;
                case "D":
                    locationY++;
                    break;
            }
        }
        System.out.println(locationY + " " + locationX);
    }
}

마지막에 출력할 때 (locationY, locationX) 임에 주의

각 명령마다 X의 값과 Y의 값 증감하는거에서 실수했다.. 제대로 생각하고 구현하기

  • String moveInput = s.nextLine();

    String[] moveArr = moveInput.split(" ");

    → 이 두줄을 String[] moveArrd = s.nextLine.split(" ");

    이렇게 한 줄로 쓸 수 있다. 기억하고 한 줄로 쓰도록 하자

  • 움직이는 명령들을 배열에 담아서 배열로 다루어도 괜찮을 듯..


시각 (113p)

내 풀이

public class Implementation4_2_1 {
    // 내 풀이
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int result = 0;
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j < 60; j++) {
                for (int z = 0; z < 60; z++) {
                    boolean strI = String.valueOf(i).contains("3");
                    boolean strJ = String.valueOf(j).contains("3");
                    boolean strZ = String.valueOf(z).contains("3");
                    if (strI || strJ || strZ) result++;
                }
            }
        }
        System.out.println(result);
    }
}
  • contains() 메서드는 String에 인자값이 포함되어 있는지 확인해 준다.
  • i의 범위를 i < n이 아닌 i ≤ n 으로 설정하는 것에 주의하기

오늘 한 일

  • 이번 주말 학습은 알고리즘 두문제밖에 못 풀었다...

0개의 댓글