/** dataset.ts中
* Shuffles the array using Fisher-Yates algorithm. Uses the seedrandom
* library as the random generator.
*/
export function shuffle(array: any[]): void {
let counter = array.length;
let temp = 0;
let index = 0;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
}
在playground.ts中引入与使用:
import{Example2D, shuffle} from "./dataset";
let data = generator(numSamples, state.noise / 100);
// Shuffle the data in-place.
shuffle(data);
编译后试运行一下
"use strict";
exports.__esModule = true;
exports.shuffle = void 0;
/**
* Shuffles the array using Fisher-Yates algorithm. Uses the seedrandom
* library as the random generator.
*/
function shuffle(array) {
var counter = array.length;
var temp = 0;
var index = 0;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
}
exports.shuffle = shuffle;
var obj = {};
obj.arr = [1,2,3,4,5,6]; /*严格模式下无法意外创建全局变量*/
shuffle(obj.arr)
console.log(obj.arr)
Fisher-Yates algorithm:原始的方式RangeRollScratchResultA B C D E F G H1–83A B C D E F G HC1–74A B C D E F G HC E1–65A B C D E F G HC E G1–53A B C D E F G HC E G D1–44A B C D E F G HC E G D H1–31A