Article Directory
Preface
Use Scala's syntax to shuffle the array
1. What is a scrambled array?
Shuffle an array with no duplicate elements. Example: // Initialize the array with the number set 1, 2 and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return the result. Any permutation of [1,2,3] should return the same probability. solution.shuffle(); // Reset the array to its initial state [1,2,3]. solution.reset(); // Randomly return the result of the array [1,2,3] scrambled. solution.shuffle();
2. Concrete realization
code show as below:
class Solution(_nums: Array[Int]) { val nums = _nums /** Resets the array to its original configuration and return it. */ def reset(): Array[Int] = { this.nums } /** Returns a random shuffling of the array. */ //The idea of the shuffling algorithm is to randomly select an element from the subscript range of [0, len] each time and exchange it with the element at the current index subscript position. def shuffle(): Array[Int] = { val len = nums.length var arr = nums.toBuffer//Create a new array for (index <- 0 until len) { var RandomIndex: Int = Random.nextInt(len ) val tmp = arr(index) arr(index) = arr(RandomIndex) arr(RandomIndex) = tmp } arr.toArray } }