본문 바로가기
Study with me/프로그래머스 L0 마스터하기

프로그래머스 - L0 순서바꾸기

by 외계나무 2023. 12. 25.

프로그래머스 - level 0 순서 바꾸기

// 1차
class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] answer = new int[num_list.length];
        int i = n;
        for(int j=0; j<answer.length; j++) {
            if(i == num_list.length) i=0;
            answer[j] = num_list[i++];
        }
        return answer;
    }
}
// 2차시
class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] answer = new int[num_list.length];
        for(int i=0; i<num_list.length; i++) {
            answer[i] = num_list[(i+n)%num_list.length];
        }
        return answer;
    }
}

처음부터 나머지 연산 쓰고 싶었는데 잠깐 헤매는 바람에 일단 Brute-force로 되는대로 풀고 다시 풀어보았다.

타인의 풀이 중, 나머지 연산 + Stream 풀이가 있길래 가져와 봄.

import java.util.stream.IntStream;

class Solution {
    public int[] solution(int[] num_list, int n) {
        return IntStream.range(0, num_list.length)
        		.map(i -> num_list[(i + n) % num_list.length])
        		.toArray();
    }
}