Skip to content

洗牌函数

将一个数组随机打乱顺序,如[1,2,3,5,8,9] -> [9,5,2,3,8,1]。可以实现这样功能的函数,我们称之为洗牌函数。

这里使用类来进行封装,先封装一个随机类,再通过随机类使数组索引随机互换。

javascript
class SuperRandom {
    constructor(params,type) {
        if(!params || !type){
            // 空构造时调用
            this.help();
            return false;
        }

        this.#randomParam = params; // 需要去处理的参数
        if(!this.#canType.includes(type)){
            // 无类型或类型错误时调用
            console.log('类型错误');
            return false;
        }

        // 正确时进行的运算
        this.random()[type]();
    }

  
    #randomParam = [];                       // 需要去处理的参数
    returnParam = '';                       // 声明处理完成后返回的参数
    #canType = Object.keys(this.random());   // 可以处理的类型方法

    random(){
        return {
            // 该方法根据区间生成随机的整数
            integer: () => {
                if(this.#randomParam.length !== 2){
                    console.log('请输入有两个值的数组')
                    return false;
                }

                this.returnParam = Math.floor(Math.random() * (this.#randomParam[1] - this.#randomParam[0] + 1)) + this.#randomParam[0];
            },
            // 该方法随机给出数组中含有的数
            enum: () => {
                let temp = this.#randomParam
                this.#randomParam = [0,temp.length - 1]
                this.random().integer()
                this.#randomParam = temp
                this.returnParam = this.#randomParam[this.returnParam]
            }
        }
    }

    help(){
        console.log('必需两个参数:要处理的字符串、处理类型')
        console.group('可传类型:');
        this.#canType.forEach(e => {
            console.log(e);
        });
        console.groupEnd();
    }
}

class ShuffleFn {
    constructor(arr) {
       this.arr = arr 
       this.shuffle();
    }
    arr = []
    returnParam = []
    shuffle(){
        let temp = [...this.arr];
        let length = this.arr.length;
        this.arr.forEach((e,i) => {
            let randomIndex = new SuperRandom([0,length-1],'integer').returnParam;
            this.arr[i] = this.arr[randomIndex];
            this.arr[randomIndex] = e;
        })
        this.returnParam = [...this.arr];
        this.arr = [...temp];
    }
}

let main = new ShuffleFn([1,2,3,5,7,9])
console.log(main)

鄂ICP备19018246号-1