【发布时间】:2020-08-27 10:17:04
【问题描述】:
我正在创建一个教师教学计划,该计划应分配多个独特的教师来教授另一位教师。
我正在使用一组数组来捕获和随机化组和教师列表。在这个脚本中,我使用了 3 级数组。这对于长列表和许多组来说效率低吗?
//Shuffle and create groups
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
const Tgroups = [[3,[1, 2]], [4,[5,6]], [7,[8,9]],[10,[11,12]]];
//const Tgroups = [[1, 2], [5,6], [8,9],[11,12]];
Tgroups.forEach(shuffle);
shuffle(Tgroups);
console.log("shuffled:", Tgroups.join(" | "))
const Tlist = [].concat(...Tgroups);
console.log("Tlist:", Tlist);
我已经能够将一位老师与另一位老师配对。
// match the group with the list:
const pairs = [];
for(let i = 0; i < Math.floor(Tlist.length / 2); i++) {
pairs.push([
Tlist[i],
Tlist[i + Math.floor(Tlist.length / 2)]
]);
}
if(Tlist.length % 2)
pairs.push([Tlist.pop()]);
console.log("pairs:", pairs.join(" | "));
const result = [].concat(...pairs);
但是,我不相信我正在使用以下方法创建多对一关系
for(let i = 0; i < result.length; i++)
{
var innerArrayLength = result[i].length;
for (let j = 0; j < innerArrayLength; j++)
{
//console.log('[' + i + ',' + j + '] = ' + result[i][j]);
console.log(result[i] + " -> " + result[(i + 2) % result.length]);
}
请问有什么方法可以达到更好的效果吗?
【问题讨论】:
-
你不能只为每个老师使用一个对象,并用一个 id 指示将教他们的老师吗?这将消除对 3d 数组的需要
-
@Kobe 老师是随机选择和分配的,不是预先确定的。
标签: javascript arrays random shuffle