[Leetcode/Python] Shuffle an Array

지구인 ㅣ 2022. 8. 27. 00:12

728x90
Top Interview Questions 의 Easy Collection에 있는 문제입니다.        
문제는 여기서 볼 수 있습니다.

 

Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.

Implement the Solution class:

  • Solution(int[] nums) Initializes the object with the integer array nums.
  • int[] reset() Resets the array to its original configuration and returns it.
  • int[] shuffle() Returns a random shuffling of the array.

 

Example 1:

Input
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
Output
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

Explanation
Solution solution = new Solution([1, 2, 3]);
solution.shuffle();    // Shuffle the array [1,2,3] and return its result.
                       // Any permutation of [1,2,3] must be equally likely to be returned.
                       // Example: return [3, 1, 2]
solution.reset();      // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
solution.shuffle();    // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]

 

Constraints:

  • 1 <= nums.length <= 50
  • -106 <= nums[i] <= 106
  • All the elements of nums are unique.
  • At most 104 calls in total will be made to reset and shuffle.

 

Code:

from random import random
class Solution:

    def __init__(self, nums: List[int]):
        self.array = nums

    def reset(self) -> List[int]:
        return self.array

    def shuffle(self) -> List[int]:
        return sorted(self.array, key=lambda _: random())


# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
# 새로 배운 것 : key=lambda _: random()

 

문제 풀이

(*discussion 탭 참고)

- reset과 shuffle 기능이 있는 class를 만드는 문제이다.

- init 메서드 : 객체를 생성할 땐, 리턴할 것이 없다. 객체만 생성한다. input으로 들어온 리스트로 array를 초기화한다. self.array의 array는 임시적으로 만든 변수명이니 자유롭게 설정해도 된다.

- reset 메서드 : init메서드에서 초기화한 array를 반환한다.

- shuffle 메서드 : array 자체의 변형 없이 랜덤하게 각 요소가 섞인 리스트를 리턴한다. 랜덤하게 섞기 위해서 sorting의 기준은 random()함수를 적용했다. lambda _ 의 _(언더바)는 for _ in range(n)의 언더바처럼, 특별히 사용되지 않을 때 쓴다. 직관적으로 key가 random()이라는 것으로 생각하면 편할 것 같다.

 

lambda 함수에 변수 설정 없이 _ (언더바)를 사용하는 것이라든가, 조건으로 random()을 사용하는 것은 처음 접해서 굉장히 생소했다.

배운 것 :  lambda _ : random() 

728x90