Iterating over a list in pseudo-random order without storing a shuffled list

前端 未结 5 608
失恋的感觉
失恋的感觉 2021-01-02 08:10

In a game, we use a technique called \'colour picking\' to select units.

This means that every visible unit is given a unique colour.

Here is an example of a

5条回答
  •  青春惊慌失措
    2021-01-02 08:30

    I don't really see the problem. As I wrote in the comments, you need only 128K to store a permutation of [0..64K), and you don't need any allocations inside the main loop. Here's a stateful color store in C++11 (in older C++, use a vector or new[]):

    class ColorPicker {
        std::array colors;
        uint16_t idx;
    
      public:
        ColorPicker() : idx(0)
        {
            std::iota(colors.begin(), colors.end(), 0);
            std::random_shuffle(colors.begin(), colors.end());
        }
    
        uint16_t next_color()
        {
            return colors[idx++];
        }
    };
    

    You only need one of these structures. Now, whenever you create a new unit, call next_color on the ColorPicker and store it on the unit as an attribute.

    This solution will cycle though the colors. If that's not desired, do a random_shuffle each time the index wraps around to zero.

提交回复
热议问题