본문 바로가기

프로그래머스/lv0

배열 회전시키기

/* 배열 회전시키기
 * 정수가 담긴 배열 numbers와 문자열 direction가 매개변수로 주어집니다.
 * 배열 numbers의 원소를 direction방향으로 한 칸씩 회전시킨 배열을 return
 *
 * numbers                      direction   result
 * [1, 2, 3]                    "right"     [3, 1, 2]
 * [4, 455, 6, 4, -1, 45, 6]    "left"      [455, 6, 4, -1, 45, 6, 4]
 */

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class programmer_0_78 {
    static int[] a1 = {123};                 static String b1 = "right";
    static int[] a2 = {445564-1456}; static String b2 = "left";
    public int[] solution(int[] numbers, String direction) {
        int[] answer = new int[numbers.length];
 
        for(int i = 0; i < numbers.length; i++){
            if(direction.equals("right")){
                if(i-1 < 0) answer[i] = numbers[numbers.length-1];
                else     answer[i] = numbers[i-1];
            }
            else{
                if(i+1 >= numbers.length)    answer[i] = numbers[0];
                else    answer[i] = numbers[i+1];
            }
        }
        for(int n : answer) System.out.println(n);
        return answer;
    }
    public static void main(String args[]){
        programmer_0_78 t = new programmer_0_78();
        // System.out.println("---------------------------------------");
        // System.out.println("result = " + t.solution(a1,b1));
        System.out.println("---------------------------------------");
        System.out.println("result2 = " + t.solution(a2,b2));
        System.out.println("---------------------------------------");
        // System.out.println("result3 = " + t.solution(a3,b3));
        // System.out.println("---------------------------------------");
    } 
}
 
cs

'프로그래머스 > lv0' 카테고리의 다른 글

2차원으로 만들기  (0) 2022.12.02
공 던지기  (0) 2022.12.02
주사위의 갯수  (0) 2022.12.02
합성수 찾기  (0) 2022.12.02
팩토리얼  (0) 2022.12.02