Efficiently creating pairs of random array items in PHP that meet certain criteria -


i have 3 arrays:

$a 5 elements, , $b & c 4 elements.

each member of $a has paired randomly 3 times member $b or $c. however, each element $b , $c has paired randomly five elements other 2 arrays.

each of these pairings must unique, , element can't paired itself.

eg:

$a = array('a1', 'a2', 'a3', 'a4', 'a5'); $b = array('b1', 'b2', 'b3', 'b4'); $c = array('c1', 'c2', 'c3', 'c4'); 

the pairings a1 like:

'a1', 'b3' 'a1', 'b4' 'a1', 'c2' 

and pairings c3 like

'c3', 'a2' 'c3', 'b3' 'c3', 'a4' 

so again, i'm trying make random pairings that:

  1. an element must matched elements other arrays (and can't match themselves). can in number either one.
  2. each matching must unique
  3. elements in $a must matched 3 times, elements in $b or $c must matched 5 times, except (edit!) 1 element $c can matched 4 times.

i found solution works shuffling arrays , checking see if line up, slow -- takes 100-5000 attempts 1 works. since simulation occur thousands/millions of times, not going cut it. i'm hoping there's approach generate these pairings on first try.

so using advice dave, figured out. i'm sure there's easier way it, here's gist of did:

prepwork -- create array $b can matched $c

  1. make array contains each member of $b 5 times.

  2. shuffle array, , cut after 8th member. first part goes 1 array, we'll call $a_choices. second part, we'll call $b_choices, call array_count_values() , determine how many times each element appears.

  3. make array contains each member of $c 5 times (except 1 appear 4x), we'll call $c_list. using histogram above, make array elements of $c based on how many times member appears. eg, if members $b appeared 3x, 3x, 4x, , 2x, need 4 elements $c: 2 appear 4x, 1 that's 3x, , 1 that's 1x. these put array, $c_choices. elements picked randomly $c_list, , moved array , put $c_choices.

  4. call array_merge($a_choices, $c_list) merge what's leftover. there 15 elements $a grab from, , there 12 leftover both $c , $b.

select matches $a first

  1. go through each element in $a, , make 3 random choices $a_choices. however, if element appears often, needs grabbed time. eg, if i'm matching second-to-last element in $a, need grab element $a_choices appears twice. if i'm selecting third-to-last, grab elements appear 3x. etc. makes sure last element $a can make 3 unique matches.

match $b

  1. now using elements in $b, match them elements $c_choices in same way did elements $a -- again making sure select elements appear often. whole point of prepwork part make sure there right combination of elements $b , $c leftover make match every time.

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -