【发布时间】:2020-12-01 22:44:59
【问题描述】:
例如,
const text = "APPLE ORANGE";
const text_position = [0,4,4,7,9];
const inserted_value = ["yo","wo","go","lo","zo"];
对于这个例子,我想创建一个这样的数组:
return ["yo","APPL","wo","go","E O","lo","RA","zo","NGE"];
我的代码:
我正在尝试通过字符串位置数组从给定字符串合并到一个数组中。 给出了一个字符串和两个数组:
const content = "0123456789TEXT";
const footnote_position = [0, 1, 2, 2, 6]; // string positions
const footnote_value = ["ZERO", "ONE", "TWO", "TWO", "SIX"]; // inserted values
但是对于我的代码及以上给出的content、footnote_position和footnote_value,算法必须输出如下:
["ZEROR","0","ONE","1","TWO","TWO","2345","SIX","67899TEXT"]
我的完整代码是:
const content = "0123456789TEXT";
const footnote_position = [0, 1, 2, 2, 6]; // must be sorted
const footnote_value = ["ZERO", "ONE", "TWO", "TWO", "SIX"];
const position_set = [...new Set(footnote_position)]; // must be sorted 1,2,6
const contentArray = [];
let textArray = [];
let prev = -1;
let count = footnote_position.length;
for (let index = 0; index < count + 1; index++) {
switch (index) {
case 0: // ok
var item = footnote_position[index];
if (item != 0) {
textArray.push(content.substring(0, item));
}
footnote_position.forEach((value, position) => {
if (value == item) {
textArray.push(footnote_value[position]);
}
})
prev = item;
break;
case length: // ok
textArray.push(content.substring(prev)); // <Text>
footnote_position.forEach((value, position) => {
if (value == item) textArray.push(footnote_value[position]);
})
break;
default: // not ok
var item = footnote_position[index];
textArray.push(content.substring(prev, item));
footnote_position.forEach((value, position) => {
if (value == item) textArray.push(footnote_value[position]);
})
prev = item;
break;
}
}
console.log(textArray);
不幸的是,我的输出不同如下:
["ZERO", "0", "ONE", "1", "TWO", "TWO", "", "TWO", "TWO", "2345", "SIX", "6789TEXT"]
出了什么问题?对于这个问题,您有任何替代的不同算法解决方案吗?
另外,我真的不知道为什么case length: 有效。代码中没有定义变量length。
【问题讨论】:
-
从给定的例子中我真的不明白这个算法背后的逻辑。你介意解释一下吗?
-
是的,我添加了一个示例,请您重新阅读问题吗? @msmolcic
标签: javascript arrays algorithm merge