在 JavaScript 中基于字符矩阵和数字数组构造字符串


问题

我们需要编写一个 JavaScript 函数,该函数输入一个字符串字符的 n * n 矩阵和一个整数数组(正数且唯一)。

我们的函数应构造一个字符串,其中那些字符的基于 1 的索引存在于数字数组中。

字符矩阵 −

[
   [‘a’, ‘b’, ‘c’, d’],
   [‘o’, ‘f’, ‘r’, ‘g’],
   [‘h’, ‘i’, ‘e’, ‘j’],
   [‘k’, ‘l’, ‘m’, n’]
];

数字数组 −

[1, 4, 5, 7, 11]

应返回“adore”,因为这些是矩阵中数字数组指定的基于 1 的索引处存在的字符。

示例

以下是代码 −

 实时演示

const arr = [
   ['a', 'b', 'c', 'd'],
   ['o', 'f', 'r', 'g'],
   ['h', 'i', 'e', 'j'],
   ['k', 'l', 'm', 'n']
];
const pos = [1, 4, 5, 7, 11];
const buildString = (arr = [], pos = []) => {
   const flat = [];
   arr.forEach(sub => {
      flat.push(...sub);
   });
   let res = '';
   pos.forEach(num => {
      res += (flat[num - 1] || '');
   });
   return res;
};
console.log(buildString(arr, pos));

输出

以下是控制台输出 −

adore

更新于:20-Apr-2021

151 次浏览

开启您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.