This C++ solution is generating a nondescriptive runtime error


  • 0
    H
    class Solution {
    public:
        vector<int> original;
    
        Solution(vector<int> nums) {
            original = nums;
            srand(time(NULL));
        }
    
        /** Resets the array to its original configuration and return it. */
        vector<int> reset() {
            return original;
        }
    
        /** Returns a random shuffling of the array. */
        vector<int> shuffle() {
            vector<int> shuffled = original;
        
            for (int i = 0; i < shuffled.size()-1; i++) {
                int j = rand() % (shuffled.size()-i) + i;
                swap(shuffled[i], shuffled[j]);
            }
        
            return shuffled;
        }
    };
    

    All it tells me when trying to submit is "Runtime Error". Any ideas why?


  • 1
    S

    Got similar error. in your code
    for (int i = 0; i < shuffled.size()-1; i++) {
    what happens when your array is empty? Size of an array can be unsigned int 0 and if you do -1 you will get 0xFFFFFFFFFF and thereby you will try to access an array which is definitely Out Of Range.

    simply add in the beginning of a function the verification like next:
    if (original.size() < 1) return original;

    from another side, there is no reason to shuffle numbers if you have none or 1 number. result should be the same.

    hope it helps :)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.