随机化数组中的项目并保持原始顺序

randomize items in an array and keep original order

我想随机化正在输出的电子邮件地址并删除重复项并让它们保留原始顺序。当我不随机化时,这非常有效。我生成了电子邮件,删除了重复项并输出,没有任何问题。我也没有随机化的问题。我似乎遇到的问题是将两者结合起来。能够生成数组、随机化、删除重复项并保留原始顺序。以下是我已经尝试过的,这是我得到的最接近的。感谢您的帮助。

function randomize(arr) {
    var i, j, tmp;
    for (i = arr.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    return arr;
}
const sourceArray = [];

var arr = sourceArray;

// we start with an empty source array
// const sourceArray = [];

// the number of emails / 2
const numberOfEmails = 100000;

// first pass we add 100,000 emails
for (let index = 0; index < numberOfEmails; index++) {
  sourceArray.push(`test${index}@google.com`);
}

// second pass we create dupes for all of them
for (let index = 0; index < numberOfEmails; index++) {
  sourceArray.push(`test${index}@google.com`);
}

// throw in some extra dupes for fun
sourceArray.push(`test0@google.com`);
sourceArray.push(`test0@google.com`);
sourceArray.push(`test0@google.com`);
sourceArray.push(`test0@google.com`);
sourceArray.push(`test0@google.com`);
sourceArray.push(`test0@google.com`);
sourceArray.push(`test0@google.com`);

// this serves as a map of all email addresses that we want to keep
const map = {};

// an exact time before we run the algorithm
const before = Date.now();

// checks if the email is in the hash map
const isInHashmap = (email: string) => {
  return map[email];
};

// iterate through all emails, check if they are in the hashmap already, if they are we ignore them, if not we add them.
sourceArray.forEach((email) => {
  if (!isInHashmap(email)) {
    map[email] = true;
  }
});

// we fetch all keys from the hashmap
const result = Object.keys(map);

arr = randomize(arr);

console.log(`Randomized here: ${sourceArray}`);

console.log(`The count after deduplicating: ${result.length}`);

// gets the time expired between starting and completing deduping
const time = Date.now() - before;

console.log(`The time taken: ${time}ms`);

console.log(result);

如果我没理解错的话,为了得到你随机排列的电子邮件,我会做以下事情:

const arrayOfEmails = [];
for (let i = 0; i < 100000; i++) {
  const randomInt = Math.floor(Math.random() * 100000); // random number between 0 and 999,999
  arrayOfEmails.push(`test${randomInt}@google.com`);
}

然后希望这有助于消除欺骗和保持秩序。

你可以

const array = [2,7,5,9,2,9,5,3,2,9]; // your random array
const set = new Set(array); // {2,7,5,9,3} javascript sets need unique members
const newArray = Array.from(set); // [2,7,5,9,3]

这是我能想到的最简单的方法。

如果您不想在第二步中删除重复项,那么您也可以这样写:

const setOfEmails = new Set();
for (let i = 0; i < 100000; i++) {
  const randomInt = Math.floor(Math.random() * 100000); // random number between 0 and 999,999
  setOfEmails.add(`test${randomInt}@google.com`); // will only add if the email is unique
}
const arrayOfEmails = Array.from(setOfEmails); // this array will be unique emails