Skip to content
Advertisement

How to make combination pattern like this

screenshoot here

i need help how to combination 4 field be as in a picture using javascript

Examples

Field1 : [1,2]

Field2 : [3,4]

Field3 : [5,6]

Field4 : [7,8]


Result Output :

1357 * 1358 * 1367 * 1368 * 1457 * 1458 * 1467 * 1468 * 2357 * 2358 * 2367 * 2368 * 2457 * 2458 * 2467 * 2468

Advertisement

Answer

You can do this recusively.

Imagine your input as a list of lists, e.g. [[1,2],[3,4],[5,6],[7,8]].

The first step is to remove the first array from the array so you end up with two arrays that look like this:

[1,2]
[[3,4],[5,6],[7,8]]

Then run the function again, but on the left overs, (in this case [[3,4],[5,6],[7,8]]).

Keep doing this until there are no left overs. At that point return the array that has been extracted, but modified to be an array of arrays, where each array has one of the numbers, in this case it would look like [[7],[8]]

Then as you go back up the call stack, iterate over the values in the array you extracted before recursion, and add them to copies of the arrays that were returned in the last call, so when you return from the [7,8] call, the next return will look like

[ [5,7], [5,8], [6,7], 6,8] ]

And so on and so forth until you reach

[ [1,3,5,7],
  [1,3,5,8],
  [1,3,6,7],
  [1,3,6,8],
  [1,4,5,7],
  [1,4,5,8],
  [1,4,6,7],
  [1,4,6,8],
  [2,3,5,7],
  [2,3,5,8],
  [2,3,6,7],
  [2,3,6,8],
  [2,4,5,7],
  [2,4,5,8],
  [2,4,6,7],
  [2,4,6,8] ]

And then you can use map and join to generate the string.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement