4

I'm having a hard time trying to explain what I want here. So I'll just try to explain it with some code:

// Example 1

$numbers = [1,2,3,4,5,6];

$in_each = 2;

$combinations = superFunction($numbers, $in_each);

// Result

$combinations = [
    [
        [1,2],
        [3,4],
        [5,6]
    ],
    [
        [1,3],
        [2,4],
        [5,6]
    ],
    [
        [1,4],
        [2,3],
        [5,6]
    ]
    // and so on
];


// Example 2

$numbers = [1,2,3,4,5,6];

$in_each = 3;

$combinations = superFunction($numbers, $in_each);

// Result

$combinations = [
    [
        [1,2,3],
        [4,5,6]
    ],
    [
        [1,2,4],
        [3,5,6]
    ]
    // and so on
];

It is the superFunction I need help with creating. Note the variable $in_each is key here.

The function doesn't need to be superefficient or even fail-safe. I just need something to get me started.

I've seen many different "array combo" scripts on here, but none with the option of "grouping them" like this.

Jocke Med Kniven
  • 3,909
  • 1
  • 22
  • 23
  • Why not use one of those existing combo scripts, then walk through the resultant array using [array_chunk()](http://www.php.net/manual/en/function.array-chunk.php) – Mark Baker Feb 28 '14 at 12:44
  • Do you want to have all available combinations or just keep the first/secon number at first place? – Fabio Feb 28 '14 at 12:44
  • I can't understand how your combinations are split into arrays. Obvious, they are `C(n,k)` for each `k` - but how are they split in first level of result array? – Alma Do Feb 28 '14 at 12:48

1 Answers1

2

Edit: I didn't know about this before, but array_chunk would do what you want without the effort of making a function. Didn't realize it existed. It seems as easy as array_chunk($numbers, $in_each);

The array_slice function can probably help out for doing what you want. I'm pretty sure you just want to split the $numbers array into equal parts determined by the $in_each variable.

Here's a quick example:

$numbers = [1,2,3,4,5,6]
$in_each = 2;
$combinations = array_slice($nums, 0, 0 + $in_each);

If you printed out $combinations at this point, this is what you would get:

Array
(
  [0] => 1
  [1] => 2
)

So, I would just setup superFunction as a loop that does array_slice n times where n is the length of $numbers divided by $in_each. n would also go up from zero by however big your $in_each variable is. In this case, n would count like this: 0 2 4.

Leroy
  • 544
  • 3
  • 14