homer512 icon

shuffle random merge

homer512 | PRO | 05/04/24 10:55:50 AM UTC | 0 ⭐ | 1414 👁️ | Never ⏰ | []
Python |

880 B

|

Source Code

|

0 👍

/

0 👎

#!/usr/bin/env python3
 
 
import collections
import random
 
 
def merge_random(left, right):
    choices = [0] * len(left) + [1] * len(right)
    random.shuffle(choices)
    readpositions = [iter(left), iter(right)]
    return [next(readpositions[choice]) for choice in choices]
 
 
def make_shuffle():
    sequence = [1, 2, 3, 4]
    # Step 1: Directly shuffle blocks that fit into memory
    blocks = [sequence[:2], sequence[2:]]
    for block in blocks:
        random.shuffle(block)
    # Step 2: Pairwise shuffle blocks. For more blocks, repeat
    merged_block = merge_random(*blocks)
    return merged_block
 
 
def main():
    counter = collections.Counter(
            tuple(make_shuffle()) for _ in range(1_000_000))
    for value, key in sorted((value, key) for key, value in counter.items()):
        print(value, key)
 
 
if __name__ == '__main__':
    main()
 

Comments