알고리즘/📌백준

백준: 영식이와 친구들

IMSfromSeoul 2021. 8. 21. 23:36

🏆 문제 정보

문제 난이도 : 하

문제 유형 : 구현

📌 문제

배열의 해당 값이 짝수이면 우측으로, 홀수면 좌측으로 L 만큼 움직인다. 해당 배열의 값이 M이면 멈추라.

📌 생각

오른쪽으로 이동할 때, 배열의 값이 배열 범위를 벗어난다 ->  %N 한 나머지 값을 index로 넣어주면 된다.

왼쪽으로 이동할 때, 배열의 값이 배열 범위를 벗어난다 -> %N한 나머지 값인데, 만약 index - move 의 값이 0보다 작다면, N을 더해준다.

// 좌측으로 이동의 경우
public class Main {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6};

        int move = 16; // 나와야 하는 결과값 5
        int index = 2;
        int N = 6;

        if(move > N){
            move %= N;
        }
        if(index-move<0){
            move = index-move+N;
        }
        System.out.println(arr[move]);
    }
}

📌 코드

package src.backjoon.영식이와친구들;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

/*
21.08.21
 */
public class Main {

    static int N,M,L;

    static int[] arr;

    public static void main(String[] args) throws FileNotFoundException {
        System.setIn(new FileInputStream("./src/backjoon/영식이와친구들/input.txt"));

        Scanner sc = new Scanner(System.in);

        N = sc.nextInt();
        M = sc.nextInt();
        L = sc.nextInt();

        arr = new int[N];
        int index = 0;

        while(true) {
            arr[index]++;
            if(arr[index] == M) break ;
            if(arr[index]%2 == 0){
                index += L;
                if(index >= N) index %= N;
            }else if(arr[index]%2 ==1){
                if(index-L<0) {
                    index = N-L+index;
                }else
                    index-=L;
            }
            System.out.println(Arrays.toString(arr));
            System.out.println("index = " + index);
        }
        int count =0;
        for(int i : arr){
            count += i;
        }
        System.out.println(Arrays.toString(arr));
        // 마지막 값은 count 에서 제외
        System.out.println(count-1);
    }
}