码迷,mamicode.com
首页 > 其他好文 > 详细

[TS] Swap two element in the array (mutation)

时间:2017-10-03 18:58:47      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:proc   ++   ons   span   turn   int   div   any   mode   

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;
}

 

[TS] Swap two element in the array (mutation)

标签:proc   ++   ons   span   turn   int   div   any   mode   

原文地址:http://www.cnblogs.com/Answer1215/p/7624220.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!