Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Randomly match elements between two arrays
/* eslint-disable lodash/import-scope, no-console */
const _ = require('lodash')
const aArr = _.times(4, i => String.fromCharCode(97 + i))
const bArr = _.times(3, i => String.fromCharCode(65 + i))
/**
* 随机组合数组的元素
* 具体逻辑:
* 先随机索引,两两配对。
* 如果该组合没出现过,则存储起来,反之尝试下一个组合。
* 如果索引数使用完了,则尝试下一次
*
* @param {[any]} aArr 数组 A
* @param {[any]} bArr 数组 B
* @param {Integer} [perferSize=1] 期望得到的组合数
* @returns {[[any, any]]} 返回二维数组,每个子数组都是一个随机组合
*/
function randomMatch (aArr, bArr, perferSize = 1) {
const results = new Map()
const aLen = aArr.length
const bLen = bArr.length
const maxTimes = aLen * bLen
const maxSize = Math.min(maxTimes, perferSize)
let aIdxArr = []
let bIdxArr = []
let i = 0
const safeTry = maxTimes * maxTimes
while (results.size < maxSize && ++i <= safeTry) {
refillIfEmpty(aIdxArr, aLen)
refillIfEmpty(bIdxArr, bLen)
let a = aIdxArr.shift()
let b = bIdxArr.shift()
let key = a + '.' + b
if (!results.has(key)) {
results.set(key, [aArr[a], bArr[b]])
}
}
return Array.from(results.values())
}
function getIdxArr (amount) {
return _.shuffle(_.times(amount, i => i))
}
function refillIfEmpty (arr, len) {
if (!arr.length) {
arr.push.apply(arr, getIdxArr(len))
}
}
let results = randomMatch(aArr, bArr, 9)
console.log(aArr, bArr)
console.log(results)
console.log('done!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.