본문 바로가기
프로그래머스 Algorithm

[프로그래머스] n^2 배열 자르기 Kotlin

by Echung 2024. 1. 10.

thumbnail

안녕하세요. 이번에는 프로그래머스 n^2 배열 자르기 문제를 풀어보려고 합니다. 

Problem


https://school.programmers.co.kr/learn/courses/30/lessons/87390

 

프로그래머스

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

programmers.co.kr

Solution


import kotlin.math.max

class Solution {
    fun solution(n: Int, left: Long, right: Long): IntArray {
        var answer: IntArray = intArrayOf()

        (left..right).forEach {
            answer += max(it % n + 1, it / n + 1).toInt()
        }

        return answer
    }
}
이번 문제는 배열을 자르는 문제입니다. forEach문을 사용해서 문제를 접근해보았습니다. 

 

1. 다른 사람 코드

import kotlin.math.max

class Solution {
    fun solution(n: Int, left: Long, right: Long): IntArray {
        return (left..right).map { (max(it / n, it % n) + 1).toInt() }.toIntArray()
    }
}
저의 코드와 다르게 map을 사용해서 코드의 가독성이 좀 더 좋아보여서 가져와보았습니다. 풀이 방식은 크게 다르지 않지만 그래도 가독성의 면에서 좀 더 나은 코드같습니다.

Performance

1. 내가 작성한 코드 2. 다른 사람 코드
반응형