Javascript 矩阵的所有变化

Javascript 矩阵的所有变化,javascript,algorithm,matrix,Javascript,Algorithm,Matrix,我正在尝试编写一个算法,以获取JavaScript中矩阵的所有可能变化。 以下是我想要实现的目标: blue,red male,female,other small,medium,large ----------------- blue,male,small blue,male,medium blue,male,large blue,female,small, blue,female,medium, blue,female,large blue,other,small, blue,oth

我正在尝试编写一个算法,以获取JavaScript中矩阵的所有可能变化。 以下是我想要实现的目标:

blue,red male,female,other small,medium,large ----------------- blue,male,small blue,male,medium blue,male,large blue,female,small, blue,female,medium, blue,female,large blue,other,small, blue,other,medium, blue,other,large red,male,small red,male,medium red,male,large red,female,small, red,female,medium, red,female,large red,other,small, red,other,medium, red,other,large 蓝色,红色 男、女、其他 小、中、大 ----------------- 蓝色,雄性,小 蓝色,男性,中等 蓝色,雄性,大型 蓝色,雌性,小, 蓝色,女性,中等, 蓝色,雌性,大型 蓝色的,其他的,小的, 蓝色,其他,中等, 蓝色,其他,大的 红色,雄性,小 红色,男性,中等 红色,雄性,大型 红色,雌性,小, 红色,女性,中等, 红色,雌性,大型 红色,其他,小, 红色,其他,中等, 红色,其他,大的
您知道如何做到这一点吗?

您可以使用reduce:

let data=['blue','red']
让数据2=['男性','女性','其他']
让数据3=['small','medium','large']
让结果=数据。减少((acc,rec)=>{
返回acc.concat(数据2.reduce((acc2,rec2)=>{
返回acc2.concat(data3.reduce((acc3,rec3)=>{
返回acc3.concat([`${rec},${rec2},${rec3}`])
},[]))
},[]))
},[])

console.log(result)
您可以使用reduce:

let data=['blue','red']
让数据2=['男性','女性','其他']
让数据3=['small','medium','large']
让结果=数据。减少((acc,rec)=>{
返回acc.concat(数据2.reduce((acc2,rec2)=>{
返回acc2.concat(data3.reduce((acc3,rec3)=>{
返回acc3.concat([`${rec},${rec2},${rec3}`])
},[]))
},[]))
},[])

console.log(result)
您想要的内容称为多个列表的笛卡尔乘积。如果有一组固定的列表,则嵌套循环是生成笛卡尔乘积的一种简单方法

通过以里程表样式遍历列表,可以将其推广到任意列表。(不过,里程表的每个数字可能有不同的范围。)

以下是方法:

function cartesian(m) {
    const res = [];
    const index = [];    // current index
    const max = [];      // length of sublists

    for (let i = 0; i < m.length; i++) {
        index.push(0);
        max.push(m[i].length);
    }

    for (;;) {
        res.push(index.map((i, j) => m[j][i]));

        let i = 0;
        index[i]++;

        while (index[i] == max[i]) {
            index[i] = 0;
            i++;

            if (i == m.length) return res;
            index[i]++;
        }
    }
}

这就产生了一个包含所有可能性的巨大列表,这可能并不理想。在上述代码将当前列表推送到结果数组的每个可能性中,您可以通过执行任何您想执行的操作来更改函数。上面的代码在每次迭代中更改第一项,这与您在文章中显示的内容相反。

您想要的内容称为多个列表的笛卡尔乘积。如果有一组固定的列表,则嵌套循环是生成笛卡尔乘积的一种简单方法

通过以里程表样式遍历列表,可以将其推广到任意列表。(不过,里程表的每个数字可能有不同的范围。)

以下是方法:

function cartesian(m) {
    const res = [];
    const index = [];    // current index
    const max = [];      // length of sublists

    for (let i = 0; i < m.length; i++) {
        index.push(0);
        max.push(m[i].length);
    }

    for (;;) {
        res.push(index.map((i, j) => m[j][i]));

        let i = 0;
        index[i]++;

        while (index[i] == max[i]) {
            index[i] = 0;
            i++;

            if (i == m.length) return res;
            index[i]++;
        }
    }
}
这就产生了一个包含所有可能性的巨大列表,这可能并不理想。在上述代码将当前列表推送到结果数组的每个可能性中,您可以通过执行任何您想执行的操作来更改函数。上面的代码在每次迭代中更改第一项,这与您在文章中显示的内容相反