php - Algorithm to mix any list of string (array) -


I have to find out what is the best algorithm for creating a list of all combinations of an array in PHP.

I want all possible combinations of elements in the original array. Duplicate question only seek permutations The difference is that I want to include it, for example, "22", while "22" is not in the element of permutation of this array.

Here is an example:

  Input: 1, 2, 3  

Then the output will be

  Output: 1, 2, 3, 11, 12, 13, 21, 22, 23, 31, 32, 33, 111, 112, 113, 121, 123 ... to 333.  

This question is different, because this question wants to combine all the combinations of array to a certain length, not all the serials of the array, until a certain length. Specifically, the linked question, for example, "11" or "332" will never return, while the question also seeks to obtain these values ​​as output.

This problem can be solved by typing the recursive function, where you can combine an array of combinations with a small On a combination of length, make up to a certain length. There is a special case for the length of 1. In that case, the array of combinations is similar to the original array. For all other lengths, we calculate the composition length to 1 less string than the current length, and add all the combinations of the current length.

  function combi ($ arr, $ length) {if ($ length == 1) {return $ arr; } And {$ small = cogi ($ arr, $ length - 1); $ New = array (); Foreign currency ($ prefix $ small) {if (strollon ($ prefix) == $ length - 1) {foreach ($ suffix as $ suffix) {$ new = $ prefix $ suffix}; }}} Return array_merge ($ small, $ new); }} $ A = array ("1", "2", "3"); Var_dump (comb ($ a, count ($ a)));  

This is not the fastest way, because you will loop through a rising list, while most elements become irrelevant to the creation of new strings. In addition, if your input is anything other than the strings, then you end up with the stars of a mixed array and the type of element you have started with.

This code is working.


Comments

Popular posts from this blog

java - org.apache.http.ProtocolException: Target host is not specified -

java - Gradle dependencies: compile project by relative path -

ruby on rails - Object doesn't support #inspect when used with .include -