zoukankan      html  css  js  c++  java
  • [Algorithom] Shuffle an array

    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.

    import { randomInt } from '../random/random';
    
    /**
     * Returns a shuffled version of the input array
     */
    export 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]];
      }
    
      return array;
    }
    export function randomInt(start: number, before: number) {
      return start + Math.floor(Math.random() * (before - start));
    }
  • 相关阅读:
    四则运算
    四则运算二
    学习进度条
    四则运算一
    课堂测试七
    问题与思考6
    问题与思考5
    问题与思考04
    Android SDK 目录说明
    如何判断视频的比例(4:3/16:9)和分辨率?
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10335645.html
Copyright © 2011-2022 走看看