There is a js array in which there are simple elements, for example, ordinary letters, and there are elements that are themselves arrays. It is necessary to make all the combining elements.

Example:

1 авп к 4 5п

Need to get:

1ак45, 1вк45, 1пк45, 1ак4п, ...

In general, it is necessary to make all such combinations. The length of the common array and embedded arrays is variable, the position and number of embedded arrays also vary. Throw ideas on how to organize a brute force algorithm?

  • The last combination in your example is "1pk4p"? - avp
  • Yes. It seems that there should be a simple and standard algorithm, but I still can’t make my own “bike”. And where to read in a quick way, I do not know either. Therefore, I decided to ask a question here. - Maksim36
  • If it's not a secret, why do you need it? - Zowie
  • I am developing the service "Online reproduction and rewriting of the text . " Random connections of elements work, but I still can not choose everything in a row. - Maxim36

1 answer 1

For example, in haste, like this:

 var i, j, k, arr, tmp1, tmp2, c, c1; arr = [ '1', 'авп', 'к', '4', '5п' ]; tmp1 = [ '' ]; tmp2 = []; for ( i = 0; i < arr.length; i++ ){ c = arr[ i ]; for ( j = 0; j < tmp1.length; j++ ){ c1 = tmp1[ j ]; for ( k = 0; k < c.length; k++ ){ tmp2.push( c1 + c[ k ] ); } } tmp1 = tmp2; tmp2 = []; } console.log( tmp1 ); 

PS: In the current view, the arr elements are either a string or an array

  • Thank you very much, your code managed to "get" a half-turn. At first glance, it works as it should. With a fresh mind I will see what can be improved in relation to the conditions of my task. As soon as you could understand exactly what I needed? Amazing. Thanks again. - Maksim36