@algorithm.ts/knuth-shuffle
v2.0.14
Published
Knuth shuffle
Downloads
178
Maintainers
Readme
A typescript implementation of the Knuth-Shuffle algorithm.
Knuth-Shuffle is a shuffle algorithm, which can complete the shuffle in $O(N)$ time complexity on the basis of only using a constant level of extra space.
If you are curious about this algorithm, you can visit here for more details.
Install
npm
npm install --save @algorithm.ts/knuth-shuffle
yarn
yarn add @algorithm.ts/knuth-shuffle
deno
import knuthShuffle from 'https://raw.githubusercontent.com/guanghechen/algorithm.ts/main/packages/knuth-shuffle/src/index.ts'
Usage
Shuffle nums.
import knuthShuffle from '@algorithm.ts/knuth-shuffle' knuthShuffle([1, 2, 3, 4, 5])
Shuffle complex data nodes.
import knuthShuffle from '@algorithm.ts/knuth-shuffle' interface Node { name: string email: string age: number } const nodes: Node[] = [ { name: 'alice', email: '[email protected]', age: 40 }, /*... omit ...*/ { name: 'bob', email: '[email protected]', age: 40 }, ] knuthShuffle(nodes)
Shuffle a contiguous range of the original array.
import knuthShuffle from '@algorithm.ts/knuth-shuffle' // shuffle { a[2], a[3], a[4], a[5], a[6] } knuthShuffle([1, 2, 3, 4, 5, 6, 7, 8, 9], 2, 7)