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

前端 未结 5 609
失恋的感觉
失恋的感觉 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:31

    First, use binary to store color states(1-used, 0-unused). 2^16=65536(states). If we use 1 bit for one color, 65536/8=8192 bytes are needed.
    Next question is how to manage these bytes. I suggest a tree structue: upon these 8192 bytes, another (8192/8=)1024 bytes are needed, every bit in these upper bytes representes one byte in 8192 bytes, if one of lower bytes are ALL 1, its upper bit is 1.
    This rule can expand upper and upper: 8192 -> 1024 -> 128 ... at last, to 1 byte(not fully used though).
    To use this structure, you can generate a random number in 0..7 for many times, from the root byte, if its bit is 1, try again; if its 0, down to the lower byte, repeat these action until the lowest byte is reached.
    Additionally, you can build this tree in one array: just like the heap in heapsort. (with some empty units).

    APPEND: A int16 is need for one color, once down to a lower byte, you get a three-bit binary number, append them from left to right to the color number: int16. (The root byte represent only 2 states, and only generate 1-bit binary number, its form is 111111??.

提交回复
热议问题