神经网络游戏场06:shuffle的实现 Fisher-Yates algorithm - dataset.ts

Fisher-Yates algorithm:

原始的方式

RangeRollScratchResult
A B C D E F G H
1–83A B C D E F G HC
1–74A B C D E F G HC E
1–65A B C D E F G HC E G
1–53A B C D E F G HC E G D
1–44A B C D E F G HC E G D H
1–31A B C D E F G HC E G D H A
1–22A B C D E F G HC E G D H A F
A B C D E F G HC E G D H A F B

由于计算机swap转换方式进行的优化

RangeRollScratchResult
A B C D E F G H
1–86A B C D E H GF
1–72A G C D E HB F
1–66A G C D EH B F
1–51E G C DA H B F
1–43E G DC A H B F
1–33E GD C A H B F
1–21GE D C A H B F
counter=counter-1;index = Math.floor(Math.random() * counter);temp = array[counter];array[counter] = array[index];array[index] = temp;

typescript代码

/**  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)
node shuffle.js
# 输出为:[2,3,6,1,4,5]

参考与更多

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值