2

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.

kenlukas
  • 3,616
  • 9
  • 25
  • 36
Ali Husham
  • 816
  • 10
  • 31

2 Answers2

2

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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)])
sa_n__u
  • 336
  • 1
  • 9
  • That does not produce the desired result. – 001 Dec 17 '20 at 17:25
  • `In python everything is simple.` when you using libraries things will go simple in any language in javascript there are also such libraries and if there is not i can create one also in pure python you should use tow for loops to achieve that. – Ali Husham Dec 18 '20 at 04:00
  • @All You create a library and let me know. I will use that :) – sa_n__u Dec 18 '20 at 05:18