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

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10335645.html