Random sequence iteration in O(1) memory?

前端 未结 6 1471
[愿得一人]
[愿得一人] 2021-02-19 07:58

Say you want to iterate over a sequence [0 to n] in a random order, visiting every element exactly once. Is there any way to do this in O(1) memory, i.e. without creati

6条回答
  •  难免孤独
    2021-02-19 08:28

    Well... think about that for a second. How would you 'know' which elements had been visited before?

    Short answer: you can't. (Edit Well, not unless you count stateless Pseudo-random generators, but as you have stated yourself in the command, that doesn't seem feasible for the general case)

    Depending on the actual sequence, it might, however, be feasible to 'mark' elements as visited _in-place_ thus technically requiring O(n) storage, but no extra storage for the algorithm

    Example:

    const int VISITED_BIT = 0x8000; // arbitrary example
    
    bool extract(int i) { return (i & ~VISITED_BIT); }    
    bool visited(int i) { return (i & VISITED_BIT); }    
    bool markvisited(int& i) { i |= VISITED_BIT); }
    
    int main()
    {
        std::vector v = {2,3,4,5,6};
    
        int remain = v.size();
        while (remain>0)
        {
            size_t idx = rand(); // or something
            if (visited(v[idx]))
                continue;
    
            std::cout << "processing item #" << idx << ": " << extract(v[idx]) << "\n";
            markvisited(v[idx]);
            remain--;
        }
    }
    

提交回复
热议问题