FISHER-YATES洗牌算法

  • A+
所属分类:javascript 算法

function shuffle( arr ){
      if( !Array.isArray( arr ) ) throw new Error( 'paramter must be an array!' )
      let len = arr.length;
      let index = null;
      while( --len ){
            index = Math.floor( Math.random()*(len+1) )
            arr[index] = [ arr[len], arr[len] = arr[index] ][0]
      }
      return arr;
}

var arr = [1,2,3,4,5,6,7]
console.log( shuffle( arr ) )
weinxin
我的微信
欢迎来撩!!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: