javascript - 如何从数组的元素中获取不同的组合?

标签 javascript python arrays

取这个's​​tr'“ABCDE”它有以下组合“AB”,“ABC”,“ABCD”,“ABCDE”,“DE”,“CDE”,“BCDE”,“CD” ,“BC” 关于订单。我试过了

//  thi is javascript code
            const val = 'ABCDE'
            let array = []
            for (i = 0; i < val.length-1; i++) {
                  array.push(val.slice(i,val.length))
                  array.push(val.slice(0,i+2))
                  array.push(val.slice(i,val.length-i))
                  }
                  console.log(
                  array,
                  array.includes('BC'),
                  array.includes('CD')
                  )
// this is the reuslts: ["ABCDE", "AB", "ABCDE", "BCDE", "ABC", "BCD", "CDE", "ABCD", "C", "DE", "ABCDE", ""]
//this reslutes don't have compnations like 'BC' or 'CD'

我没有真正得到我需要的结果。
您对 javascript 或 python 有什么想法吗?我认为 python panda 或可能 NumPy 库有这样的东西。

最佳答案

子字符串需要两个嵌套循环。

function getAllSubstrings(str) {
    const result = [];

    for (let i = 0; i < str.length - 1; i++) {
        for (let j = i + 2; j < str.length + 1; j++) {
            result.push(str.slice(i, j));
        }
    }
    return result;
}

console.log(getAllSubstrings('ABCDE'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何从数组的元素中获取不同的组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65345175/

相关文章:

C++ 指针数组

javascript - Typescript TypeError : . .....toDateString 不是一个函数

javascript - 带有 NEW 值的闭包变量存储在哪里?

javascript - JQuery:如何来回切换图像?

python - 在 Tornado 中缓存和重用函数结果

python - 如何在pytorch对象检测中添加转换

php - 如何检查数组中的值是否存在于表中

Javascript - 如果另一个值不存在,则从数组中删除值

javascript - 如何替换不包括特定单词的字符串?

python - 了解 `scipy.spatial.Voronoi` 在 3D 中返回的脊顶点