从数组中随机选择对

Randomly select pairs from an array

本文关键字:选择 随机 数组      更新时间:2023-09-26

我有一个类似的数组

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

我想按顺序抓取、推送这些条目的随机数,并将它们推送到一个新的数组中,直到达到极限。

例如,如果我输入(5),它会将随机条目排序到一个新的数组,如

[1, 4, 7, 10, 12]

我试过

var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var newArr = [], num, roll;
//remove number from array
for(var i =0; i < arr.length; i++) {
num = Math.floor(Math.random() * arr.length);
newArr.push(arr[num]);
roll = arr.splice(num, 1);
}

但它并没有真正回报我所需要的,因为我需要留下来。我正在使用下划线,如果有帮助的话?

我认为这就是您正在努力实现的目标。使用稀疏数组并维护原始元素索引。使用等于或大于所提供数组长度的count属性将返回该数组的副本。

Javascript

/*jslint maxerr: 50, indent: 4, browser: true, bitwise: true */
/*global console */
(function () {
    "use strict";
    function customRand(array, count) {
        var length = array.length,
            indexes = [],
            result = [],
            i = 0,
            rand,
            temp;
        while (i < length) {
            if (Object.prototype.hasOwnProperty.call(array, i)) {
                indexes.push(i);
            }
            i += 1;
        }
        i = 0;
        length = indexes.length;
        while (i < length) {
            rand = (Math.random() * i) | 0;
            temp = indexes[i];
            indexes[i] = indexes[rand];
            indexes[rand] = temp;
            i += 1;
        }
        indexes = indexes.slice(0, count).sort(function (a, b) {
            return a - b;
        });
        i = 0;
        length = indexes.length;
        while (i < length) {
            result[indexes[i]] = array[indexes[i]];
            i += 1;
        }
        return result;
    }
    var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
    console.log(customRand(arr, 5));
}());

在jsfiddle 上

只是为了在这里提供帮助-你可能应该做一些类似@Eric在上的链接

function getRandomSubarray(arr, size) {
    var shuffled = arr.slice(0), i = arr.length, min = i - size, temp, index;
    while (i-- > min) {
        index = Math.floor(i * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
}
var x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var newArr = getRandomSubarray(x, 6).sort(function(a,b) { return a - b } );
console.log(newArr)

这应该会回报你想要的。虽然这对我来说太大了。使用underscore

function randomSort(a, n) {
    return _.take(_.shuffle(a), n).sort(function(a,b) { return a - b } );
}
console.log(randomSort(x, 6))

这里有另一个选项:

function getRandomSorted(arr, limit) {
  limit = limit || 1;
  var random = [];
  for (var i=0; i<limit; i++) {
    var rand = arr[0|Math.random() * arr.length];
    if (~random.indexOf(rand)){ --i; continue; }
    random.push(rand);
  }
  return random.sort(function(a,b){ return a-b });
}
getRandomSorted(arr, 5);

这将适用于字符串和数字。