Controlling distance of shuffling

后端 未结 7 1945
醉梦人生
醉梦人生 2020-12-05 05:26

I have tried to ask this question before, but have never been able to word it correctly. I hope I have it right this time:

I have a list of unique elements. I want t

7条回答
  •  无人及你
    2020-12-05 05:48

    Here's an adaptation of @גלעד ברקן's code that takes only one pass through the list (in random order) and swaps only once (using a random choice of possible positions):

    from random import choice, shuffle
    
    def magicFunction(L, d):
      n = len(L)
      swapped = [0] * n     # 0: position not swapped, 1: position was swapped
      positions = list(xrange(0,n))         # list of positions: 0..n-1
      shuffle(positions)                    # randomize positions
      for x in positions:
        if swapped[x]:      # only swap an item once
          continue
        # find all possible positions to swap
        possible = [i for i in xrange(max(0, x - d), min(n, x + d)) if not swapped[i]]
        if not possible:
          continue
        y = choice(possible)        # choose another possible position at random
        if x != y:
          L[y], L[x] = L[x], L[y]   # swap with that position
          swapped[x] = swapped[y] = 1       # mark both positions as swapped
      return L
    

    Here is a refinement of the above code that simply finds all possible adjacent positions and chooses one:

    from random import choice
    
    def magicFunction(L, d):
      n = len(L)
      positions = list(xrange(0, n))        # list of positions: 0..n-1
      for x in xrange(0, n):
        # find all possible positions to swap
        possible = [i for i in xrange(max(0, x - d), min(n, x + d)) if abs(positions[i] - x) <= d]
        if not possible:
          continue
        y = choice(possible)        # choose another possible position at random
        if x != y:
          L[y], L[x] = L[x], L[y]   # swap with that position
          positions[x] = y
          positions[y] = x
      return L
    

提交回复
热议问题