【问题标题】:JS - efficient way to map a list of strings to an equal length matrixJS - 将字符串列表映射到等长矩阵的有效方法
【发布时间】:2017-04-17 08:50:03
【问题描述】:

我正在查看problem solution on leetcode,并且有一个巧妙的解决方案,它使用 Python 的 map 函数将字符串列表转置为等大小的矩阵,如下所示:

t = map(None, *words)

解释

地图(无,...)转置“矩阵”,用无填充缺失的点。例如:

["abc",           [('a', 'd', 'f'),
 "de",     =>      ('b', 'e', None),
 "f"]              ('c', None, None)]

我想知道我是否可以通过 js gist 实现类似的目标

【问题讨论】:

  • 您只是想知道还是尝试过什么?把编程作业伪装成问题是不好的。

标签: javascript python dictionary matrix


【解决方案1】:

创建一个矩阵(等长):

solution=array.reduce((solution,el)=>(el.split("").forEach((letter,index)=>(solution[index]=solution[index]||[]).push(letter)),solution),[]);
//if you really need the *undefineds* :
maxlength=array.reduce((length,arr)=>Math.max(length,arr.length),0);
solution.forEach(el=>el.length=maxlength);

http://jsbin.com/nisoderini/edit?console 解释离开是有原因的......

检查数组中的等长数组:

length=array.reduce((length,arr,i)=>!i?arr.length:(length?(arr.length==length?length:false):false),0);

如果数组不是对称矩阵,则长度为假...

检查方阵

square=array.every(arr=>arr.length==array.length);

【讨论】:

    【解决方案2】:

    我就是这样做的。

    function transpose(mat, replacement){
        const len = findMaxArr(mat);
        const res = [];
        // loop through each row...
        mat.map(e => {
            const currElemArr = e.split('')
            if (e.length === len) {
                res.push(currElemArr);
            } else {
                // if current row len is less than max len
                // pad it with the replacement variable
                const diff = len - e.length;
                const currElemArrPadded = currElemArr.concat(createRepArr(replacement, diff));
                res.push(currElemArrPadded);
            }
        });
        return res;
    }
    
    // create an array of inp of length len
    function createRepArr(inp, len) {
        const res = [];
        for (let i = 0; i < len; i++) {
            res.push(inp);
        }
        return res;
    }
    
    // find maximum length array of string in a string array
    function findMaxArr(mat) {
        let res = 0;
        mat.forEach(m => {
            if (m.length > res) {
                res = m.length;
            }
        });
        return res;
    }
    
    const data = ["abc", "de", "f"];
    console.log(transpose(data, 0));

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      相关资源
      最近更新 更多