洗牌算法(高纳德置乱算法)记录

Posted yongzyw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了洗牌算法(高纳德置乱算法)记录相关的知识,希望对你有一定的参考价值。

  • 原理:将最后一个数和前面n-1个数中的一个数进行交换,然后倒数第二个和前面n-2个数中的一个数进行交换.以此类推
    • 洗牌算法的python实现

      import random
      lst = list(range(10))
      for i in reversed(range(len(lst))):
          j = random.randint(0,i)
          lst[i],lst[j] = lst[j],lst[i]
      print(lst)
  • python中的random.shuffle中就用到了洗牌算法,这里贴出源码

        def shuffle(self, x, random=None):
            """Shuffle list x in place, and return None.
    
            Optional argument random is a 0-argument function returning a
            random float in [0.0, 1.0); if it is the default None, the
            standard random.random will be used.
    
            """
    
            if random is None:
                randbelow = self._randbelow
                for i in reversed(range(1, len(x))):
                    # pick an element in x[:i+1] with which to exchange x[i]
                    j = randbelow(i+1)
                    x[i], x[j] = x[j], x[i]
            else:
                _int = int
                for i in reversed(range(1, len(x))):
                    # pick an element in x[:i+1] with which to exchange x[i]
                    j = _int(random() * (i+1))
                    x[i], x[j] = x[j], x[i]
    
    
    
        def _randbelow(self, n, int=int, maxsize=1<<BPF, type=type,Method=_MethodType,BuiltinMethod=_BuiltinMethodType):
            "Return a random int in the range [0,n).  Raises ValueError if n==0."
    
            random = self.random
            getrandbits = self.getrandbits
            # Only call self.getrandbits if the original random() builtin method
            # has not been overridden or if a new getrandbits() was supplied.
            if type(random) is BuiltinMethod or type(getrandbits) is Method:
                k = n.bit_length()  # don't use (n-1) here because n can be 1
                r = getrandbits(k)          # 0 <= r < 2**k
                while r >= n:
                    r = getrandbits(k)
                return r
            # There's an overridden random() method but no new getrandbits() method,
            # so we can only use random() from here.
            if n >= maxsize:
                _warn("Underlying random() generator does not supply \n"
                    "enough bits to choose from a population range this large.\n"
                    "To remove the range limitation, add a getrandbits() method.")
                return int(random() * n)
            if n == 0:
                raise ValueError("Boundary cannot be zero")
            rem = maxsize % n
            limit = (maxsize - rem) / maxsize   # int(limit * maxsize) % n == 0
            r = random()
            while r >= limit:
                r = random()
            return int(r*maxsize) % n

以上是关于洗牌算法(高纳德置乱算法)记录的主要内容,如果未能解决你的问题,请参考以下文章

游戏常用算法-洗牌算法

关于JavaScript的数组随机排序

洗牌算法

每日算法洗牌算法

洗牌算法

洗牌算法