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.

3
  • Why not use one of those existing combo scripts, then walk through the resultant array using array_chunk() Commented Feb 28, 2014 at 12:44
  • Do you want to have all available combinations or just keep the first/secon number at first place? Commented Feb 28, 2014 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? Commented Feb 28, 2014 at 12:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.