Need help with array type question

closed account (N0M9z8AR)
I am working on a problem which requires me to go through the same array multiple times, first every element, then every 2 elements, then every 3 elements, then every N elements, etc.

For example, I have an array of values

{1,2,3,4,5}

I first need to go through each element
{1},{2},{3},{4},{5}
then every two elements
{1,2} {2,3} {3,4} {4,5}
then every three elemnts
{1,2,3} {2,3,4} {3,4,5}
etc until a value N.

How would I do this?

Please and thank you

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

template < typename T >
void print_subsequences( const T* array, std::size_t array_sz, std::size_t subseq_sz )
{
    if( array_sz >= subseq_sz && subseq_sz != 0 )
    {
        for( std::size_t i = 0 ; i <= (array_sz-subseq_sz) ; ++i )
        {
            std::cout << "{ " ;
            for( std::size_t j = 0 ; j < subseq_sz ; ++j ) std::cout << array[i+j] << ' ' ;
            std::cout << "}  " ;
        }
        std::cout << '\n' ;
    }
}

template < typename T >
void print_all_subsequences( const T* array, std::size_t array_sz, std::size_t max_subseq_sz )
{ for( std::size_t n = 1 ; n <= max_subseq_sz ; ++n ) print_subsequences( array, array_sz, n ) ; }

template < typename T, std::size_t N >
void print_all_subsequences( const T (&array)[N], std::size_t max_subseq_sz = N )
{ print_all_subsequences( array, N, max_subseq_sz ) ; }

int main()
{
    const int a[] { 0, 1, 2, 3, 4, 5, 6 } ;
    print_all_subsequences(a) ;

    const char* const b[] { "abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz!" };
    print_all_subsequences(b) ;
}

http://coliru.stacked-crooked.com/a/55fc927b2d154bc3
Topic archived. No new replies allowed.