본문 바로가기
알고리즘/프로그래머스

[프로그래머스] 181897. 리스트 자르기 JAVA Kotlin

by Bhinney 2024. 1. 3.
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


❓ 문제

정수 n과 정수 3개가 담긴 리스트 slicer 그리고 정수 여러 개가 담긴 리스트 num_list가 주어집니다. slicer에 담긴 정수를 차례대로 a, b, c라고 할 때, n에 따라 다음과 같이 num_list를 슬라이싱 하려고 합니다.

  • n = 1 : num_list의 0번 인덱스부터 b번 인덱스까지
  • n = 2 : num_list의 a번 인덱스부터 마지막 인덱스까지
  • n = 3 : num_list의 a번 인덱스부터 b번 인덱스까지
  • n = 4 : num_list의 a번 인덱스부터 b번 인덱스까지 c 간격으로

올바르게 슬라이싱한 리스트를 return하도록 solution 함수를 완성해주세요.



제한사항
  • n 은 1, 2, 3, 4 중 하나입니다.
  • slicer의 길이 = 3
  • slicer에 담긴 정수를 차례대로 a, b, c라고 할 때
  • 0 ≤ a ≤ b ≤ num_list의 길이 - 1
  • 1 ≤ c ≤ 3
  • 5 ≤ num_list의 길이 ≤ 30
  • 0 ≤ num_list의 원소 ≤ 100

📎 예시

n slicer num_list result
3 [1, 5, 2] [1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6]
4 [1, 5, 2] [1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 4, 6]

 


✍🏻 JAVA

import java.util.ArrayList;
import java.util.Arrays;

public String solution(int n, int[] slicer, int[] num_lis) {
   switch (n) {
      case 1 -> {
         return Arrays.copyOfRange(num_list, 0, slicer[1] + 1);
      }
      case 2 -> {
         return Arrays.copyOfRange(num_list, slicer[0], num_list.length);
      }
      case 3 -> {
         return Arrays.copyOfRange(num_list, slicer[0], slicer[1] + 1);
      }
      default -> {
         ArrayList<Integer> ans = new ArrayList<>();
         for (int i = slicer[0]; i <= slicer[1]; i += slicer[2]) {
            ans.add(num_list[i]);
         }
         
         return ans.stream().mapToInt(i -> i).toArray();
      }
   }
}

✍🏻 Kotlin

fun solution(n: Int, slicer: IntArray, num_list: IntArray): IntArray {
   return when(n) {
      1 -> num_list.sliceArray(0 .. slicer[1])
      2 -> num_list.sliceArray(slicer[0] .. num_list.lastIndex)
      3 -> num_list.sliceArray(slicer[0] .. slicer[1])
      else -> num_list.slice(slicer[0]..slicer[1] step slicer[2]).toIntArray()
   }
}

 

댓글