• Javarscipt中数组或者字符串的随机排序方法


    在日常开发中,经常会遇到随机排序的需求,思路就是利用Math.random()方法,抽取随机数,让数组中的元素进行对调;

    话不多说直接上代码,方法一:基本思路就是将a中随机抽取一个元素,放入b中,再从a中删除这个被抽中的元素,时间复杂度为a的长度平方,因为要遍历两次a

     1 function shuffle(a) {
     2     var b = [];
     3     while (a.length > 0) {
     4         var index = parseInt(Math.random() * (a.length - 1));
     5         b.push(a[index]);
     6         a.splice(index, 1);
     7     }
     8     return b;
     9 };
    10 
    11 var arr = [1,2,3,4,5];
    12 
    13 shuffle(arr);  //输出[2,5,4,1,3];

    第二种方法:利用数组元素交换的方法;只遍历一次数组,时间复杂度为数组的长度

    function shuffle(a) {
        var len = a.length;
        for (var i = 0; i < len - 1; i++) {
            var index = parseInt(Math.random() * (len - i));
            var temp = a[index];
            a[index] = a[len - i - 1];
            a[len - i - 1] = temp;
        }
    }
    
    
    var arr = [1,2,3,4,5];
    
    shuffle(arr);  //输出[2,5,4,1,3];

    另一种和上面类似的方案:

     1 function  shuffle(a){
     2         var i, j,temp;
     3         for (i = arr.length - 1; i > 0; i--) {
     4             j = Math.floor(Math.random() * (i + 1));
     5             temp = arr[i];
     6             arr[i] = arr[j];
     7             arr[j] = temp;
     8         }
     9         return arr;
    10 }

    这样就可以提取出在原型链上的方法:

     1 Array.prototype.shuffle = function(){
     2     var len = this.length;
     3     for(var i=0;i<len-1;i++){
     4         var index = parseInt(Math.random()*(len-i));
     5         var temp = this[index];
     6         this[index] = this[len-i-1];
     7         this[len-i-1] = temp;
     8     }
     9 
    10     return this;
    11 }

    最后分享一种underscore.js中的方法,

     1 function random(min, max) {
     2     if (max == null) {
     3         max = min;
     4         min = 0;
     5     }
     6     return min + Math.floor(Math.random() * (max - min + 1));
     7 };
     8 
     9 
    10 function shuffle(arr) {
    11     var length = arr.length,shuffled = Array(length);
    12 
    13     for (var index = 0; index < length; index++) {
    14         var rand = random(0, index);
    15         
    16         if (rand !== index) {
    17             shuffled[index] = shuffled[rand];
    18         }    
    19         shuffled[rand] = arr[index];
    20     }
    21     return shuffled;
    22 }
  • 相关阅读:
    一些关于微电子方面的笔试题
    [JavaScript]Redeclaring variable
    [JavaScript]How to run Jasmine in Intellij/WebStorm?
    [JavaScript] Use `+` opertor to add one string and one number
    [CoffeeScript]CoffeeScript学习笔记
    Study Note for grunt
    grunt.js
    [转]Vim常用命令速查
    如何在Web Page里体验CoffeeScript的 功能
    [JavaScript] 如何使用Ruby gem运行jasmine test case
  • 原文地址:https://www.cnblogs.com/liquanjiang/p/8644328.html
Copyright © 2020-2023  润新知