Algorithm to print out a shuffled list, in-place and with O(1) memory

后端 未结 10 1414
野趣味
野趣味 2020-12-09 11:51

After reading this question I started to wonder: is it possible to have a shuffling algorithm which does not modify or copy the original list?

To make it clear:

10条回答
  •  醉话见心
    2020-12-09 12:24

    If there's enough space, you could store node's pointers in an array, create a bitmap and get random ints that point to the next chosen item. If already chosen (you store that in your bitmap), then get closest one (left or right, you can randomize that), until no items are left.

    If there's no enough space, then you could do same without storing node's pointers, but time will suffer (that's the time-space tradeoff ☺).

提交回复
热议问题