Function to even out multiple arrays

Posted by Moak on Stack Overflow See other posts from Stack Overflow or by Moak
Published on 2011-01-04T08:00:49Z Indexed on 2011/01/04 8:54 UTC
Read the original article Hit count: 170

Filed under:
|

Assume I have a function

evenOut($array, $limit){
    //returns exactly $limit items
}

and this data

$animals = array();
$animals['barn'] = array_fill(0,20, 'b');
$animals['forest'] = array_fill(0,20, 'f');
$animals['house'] = array_fill(0,20, 'h');
$animals['mountain'] = array_fill(0,20, 'm');

I want to return a maximum of 10 animals, however they should be spread out evenly among the locations they come from. so if i did
evenOut($animals,8); i'd get 2 of each('b','b','f','f','h','h','m','m',)
evenOut($animals,2); should return ('b','f')

if I have this data

$animals = array();
$animals['barn'] = array_fill(0,1, 'b');
$animals['forest'] = array_fill(0,3, 'f');
$animals['house'] = array_fill(0,8, 'h');
$animals['mountain'] = array_fill(0,1, 'm');

evenOut($animals,8); expected result would be ('b','f','f','f','h','h','h','m',)
evenOut($animals,10); expected result would be ('b','f','f','f','h','h','h','h','h','m',)

$animals = array();
$animals['barn'] = array_fill(0,0, 'b');
$animals['forest'] = array_fill(0,3, 'f');

evenOut($animals,10); expected result would be ('f','f','f')

I'm not sure how I should approach this, I am hoping there is a simple way

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays