how to get the different combinations from an array's elements?

Viewed 86

take this 'str' "ABCDE" it has the following combinations "AB", "ABC", "ABCD","ABCDE","DE", "CDE", "BCDE", "CD","BC" regarding the order. I tried

//  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'

I did not really get the results that I need.
Do you have any ideas in javascript or in python please, I think the python panda or probably NumPy library has such things.

2 Answers

You need two nested loop for the sub strings.

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

In python everything is simple.

from itertools import combinations
val = 'ABCDE'
print([''.join(l) for i in range(len(x)) for l in combinations(x, i+1)])
Related