2017-04-17 20 views
1

我期待在problem solution on leetcode,并且存在使用Python的地图功能移调字符串列表以相同的大小矩阵,像这样一个聪明的解决方案:JS - 有效的方式来字符串列表映射到长度相等矩阵

t = map(None, *words) 

说明

的地图(无,...)的转置 “基质”,填充无缺失的斑点。例如:

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

我想知道如果我可以achive与JS类似目标要旨

+0

是你,只是不知道或者你尝试过什么吗?将编程作业伪装成问题并不好。 – Tomalak

回答

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); 
0

这是我该怎么做的。

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));

相关问题