Javascript 检查数组是否可以是矩阵

Javascript 检查数组是否可以是矩阵,javascript,matrix,Javascript,Matrix,假设我们有一个长度为9的数组。这可以是一个矩阵 [ 1,2,3, 4,5,6 7,8,9 ] [ 1,2,3, 4,5,6 7,8,9,10 ] 如果我们有一个数组或长度为10,这不能是一个矩阵 [ 1,2,3, 4,5,6 7,8,9 ] [ 1,2,3, 4,5,6 7,8,9,10 ] 如何使用JS确定给定数组是否是正确的矩阵 1)通过创建新的卡盘数组,确定可以使用哪个数字(大于1,小于数组长度)将数组划分为偶数块/行 2) 检查所有均匀划分的块/行是否等于父数组的长度 const

假设我们有一个长度为9的数组。这可以是一个矩阵

[
1,2,3,
4,5,6
7,8,9
]
[
1,2,3,
4,5,6
7,8,9,10
]
如果我们有一个数组或长度为10,这不能是一个矩阵

[
1,2,3,
4,5,6
7,8,9
]
[
1,2,3,
4,5,6
7,8,9,10
]
如何使用JS确定给定数组是否是正确的矩阵

1)通过创建新的卡盘数组,确定可以使用哪个数字(大于1,小于数组长度)将数组划分为偶数块/行

2) 检查所有均匀划分的块/行是否等于父数组的长度

const chunk = (arr, n) => { 
    const newArr = [];
    for (let i = 0; i < arr.length; i++) { 
        let lastAdded = newArr[newArr.length - 1] || null;
        if (lastAdded != null && lastAdded.length != n) { 
            lastAdded.push(arr[i]);
        } else {
            newArr.push([arr[i]]);
        }
    }
    return newArr;
}
const ismatrix = (arr) => {
    for (let i = 0; i < arr.length; i++){
        if (i > 1) {
            if (arr.length % i === 0) {
                let chunked = chunk(arr, i);         
                for (let i = 0; i < chunked.length; i++) {
                    if (chunked.length == chunked[i].length) {
                        return true
                    }
                }
            } 
        } 
    }
    return false
}
const chunk=(arr,n)=>{
常数newArr=[];
对于(设i=0;i{
for(设i=0;i1){
如果(arr.length%i==0){
设chunked=chunk(arr,i);
for(设i=0;i
矩阵的定义是什么?为什么10不能是矩阵(例如2x5)?列和行必须相同吗?是的,偶数个“列”和“行”。然后,这只是一个确定长度是否为平方数的问题,即4、9、16、25等。正确!IDK为什么我没有想到这个问题?解决方案可以简化为:
const isMatrix=arr=>arr.length>1&&!(平均长度**0.5%1)