Subsegments of an array

Jun 15, 2017 at 10:38pm
Is there a certain formula to know how many subsegments exist in an array given the number of elements in an array, and also print all sub segments?[I also think the formula is n*(n+1)/2 sub arrays for any n elements array ? i tested it with a few examples and it turned out right idk the general case]

Considering that printing it shouldn't take more than 1 second, i.e less than or equal to O(10^7)
Last edited on Jun 15, 2017 at 11:02pm
Jun 15, 2017 at 11:53pm
define subsegment as it pertains to your problem.

if you are asking how many ways you can split up an array of size N, that is either the permutations or combinations, depending on how you defined it, which is a direct computation O(1).

Are you on a tape-reel mechanical relay system? Printing should be tiny fractions of a second.

O(10^7) is O(1). Constants are normalized, but I get what you are trying to say.

Last edited on Jun 15, 2017 at 11:55pm
Jun 16, 2017 at 12:38am
What's a subsegment of an array?
A quick search doesn't yield a definition. I know what a substring is, though, so i'm substituting "string" for "array" and proceeding.

A little math:
In a string of length N, there are exactly N - l + 1 substrings of length l, 1 ≤ l ≤ N.

Compute the sum from l = 1 to N of N - l + 1
Which is equal (by Gauss's formula) to N*(N + 1) / 2.

As you probably observed, for a string of length 3, there are 3 - l + 1 = 3 substrings of length l = 1, 3 - (l + 1) = 2 substrings of length 2, and 1 substring of length 3, for a total of 3 + 2 + 1 = 6 substrings.

Generating them all:
1
2
3
4
5
6
7
8
std::string const s{"abcd"};
// length l of subsequence from 1 to N
for (std::size_t l = 1; l <= s.size(); ++l) {
  // starting position of substring 
  for (std::size_t start = 0; start <= s.size() - l; ++start) {
    std::cout << s.substr(start, l) << '\n';
  }
}

Last edited on Jun 16, 2017 at 4:20am
Topic archived. No new replies allowed.