C
C
CrewCut2016-06-23 17:36:16
PHP
CrewCut, 2016-06-23 17:36:16

How to iterate over possible combinations of a string with array strings?

Let's say there is a string красная шапочкаand an array

1,
2,
3,
4,
5

An array can have any number of values ​​from 2 to 20 or more.
You need to get an array of strings, where there will be an initial string + array elements from one to a maximum of four so that the final array does not contain the same values ​​in a different order (not possible: red cap 1 2 3 and red cap 1 3 2) . Those.:
'красная шапочка 1',
'красная шапочка 1 2',
'красная шапочка 1 3',
'красная шапочка 1 4',
'красная шапочка 1 5',
'красная шапочка 1 2 3',
'красная шапочка 1 2 4',
'красная шапочка 1 2 5',
'красная шапочка 1 3 4',
'красная шапочка 1 3 5',
'красная шапочка 1 4 5',
'красная шапочка 1 2 3 4',
'красная шапочка 1 2 3 5',
'красная шапочка 1 3 4 5',
...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DTX, 2016-06-23
@CrewCut

Suppose we are first interested in strings of three elements. And the array has five elements.
We will consider elements of the form (a, b, c), where a, b, c - the index of the element in the array.
First, we take the first element and start adding one to the end in much the same way as it happens in the number systems
1 2 3 (means ( 1, 2, 3))
1 2 4
1 2 5
1 3 4 ((1, 3, 1), (1, 3, 2), (1, 3, 3) we are not interested in, because they are already were)
1 3 5
1 4 5
2 3 4
3 4 5
That's basically it.
codepen.io/DTX/pen/oLYrVG?editors=0011

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question