zoukankan      html  css  js  c++  java
  • [TS] Swap two element in the array (mutation)

    Shuffling is a common process used with randomizing the order for a deck of cards. The key property for a perfect shuffle is that each item should have an equal probability to end up in any given index.

    In this lesson we discuss the concept behind the simple modern fisher yates shuffle and implement it in JavaScript / TypeScript.

     

    function randomInt(start: number, before: number) {
      return start + Math.floor(Math.random() * (before - start));
    }
    
     function shuffle<T>(array: T[]): T[] {
      array = array.slice();
    
      for (let i = 0; i < array.length; i++) {
        const randomChoiceIndex = randomInt(i, array.length);
        [array[i], array[randomChoiceIndex]] = [array[randomChoiceIndex], array[i]]; // swap element in array
      }
    
      return array;
    }
  • 相关阅读:
    angular.js 渲染
    HTML5 与 CSS3 jQuery部分知识总结
    下拉滚动协议文本框展示样式(不可删除文本内容)
    06对象
    05数组
    1文字与字体
    04函数
    03循环
    02运算符
    01基础
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7624220.html
Copyright © 2011-2022 走看看