请使用js实现一个分组抽签的算法

要实现一个分组抽签的算法,我们首先需要明确一些要求和步骤。以下是一个简单的实现,它允许你将一组人员随机分配到指定数量的组中:

  1. 输入

    • 参与抽签的人员列表。
    • 需要的组数。
  2. 输出:每个组的人员列表。

以下是一个简单的JavaScript实现:

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

function distributeIntoGroups(participants, numGroups) {
    // 首先,打乱参与者数组以确保随机性
    const shuffledParticipants = shuffleArray([...participants]);

    // 计算每组应有的人数,以及剩余的人数
    const groupSize = Math.floor(shuffledParticipants.length / numGroups);
    const remainder = shuffledParticipants.length % numGroups;

    let groups = [];
    let startIndex = 0;

    for (let i = 0; i < numGroups; i++) {
        let endIndex = startIndex + groupSize;
        // 如果还有剩余的人数,则给前面的组多分配一个
        if (remainder > 0) {
            endIndex++;
            remainder--;
        }
        groups.push(shuffledParticipants.slice(startIndex, endIndex));
        startIndex = endIndex;
    }

    return groups;
}

// 示例使用
const participants = ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace', 'Henry'];
const numGroups = 3;

const groups = distributeIntoGroups(participants, numGroups);
console.log(groups);

这个算法首先会打乱参与者的顺序,然后根据组数将他们分配到各个组中,尽量确保每组人数相等,但如果参与者数量不能被组数整除,那么多出来的人会依次被分配到前面的组中。

posted @ 2025-01-04 10:24  王铁柱6  阅读(64)  评论(0)    收藏  举报