y u no do it?

Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

Starts at just \$1 per CPM or \$0.10 per CPC.

# Permutation Function

Discussion in 'PHP' started by Forbidd3n, Jul 12, 2013.

1. #1
I have been trying for about 2 days now to get this to work. I am trying to create a permutation function that will take an array and a size as arguments. It will loop through the array and create all the possible permutations with a size of the passed size argument. An example will be as follows.

\$array = range('A','E'); //any range would be allowed.

If I passed this array with a size of 2 I would get the following result...

AB, BA
AC, CA
AE, EA
BC, CB
BD, DB
BE, EB
CD, DC
CE, EC
DE, ED
and so on...

---
If I passed this array with a size of 3 I would get the following result...

ABC, ACB
BAC, BCA
CAB, CBA
and so on...

--
If I passed this array with a size of 4 I would get the following result...

ABCD, ABDC, ABCE, ABEC, ABDE, ABED,
ACBD, ACDB, ACBE, ACEB, ACDE, ACED

and so on for any size passed, unless it isn't possible meaning if the size is larger than the array count.

--
Anyone that can help me with this I wouldn't mind a donation on paypal if it works correctly in all aspects.

Last edited: Jul 12, 2013
Jul 12, 2013 IP
2. ### scriptjerkActive Member

Messages:
43
4
1
Trophy Points:
58
#2
this works for me.

``````
function pc_permute(\$items, \$perms = array( )) {
if (empty(\$items)) {
print join(' ', \$perms) . "<br/>";
}  else {
for (\$i = count(\$items) - 1; \$i >= 0; --\$i) {
\$newitems = \$items;
\$newperms = \$perms;
list(\$foo) = array_splice(\$newitems, \$i, 1);
array_unshift(\$newperms, \$foo);
pc_permute(\$newitems, \$newperms);
}
}
}

\$value = array('a','b','c','s');
\$a = pc_permute(\$value);
print_r(\$a);

``````
PHP:
Now to get to the formatting you want, you may have to replace '<br/>' from the function with your delimiter such as ', '

Jul 13, 2013 IP
3. ### Forbidd3nWell-Known Member

Messages:
262
4
0
Trophy Points:
108
#3
Thanks, but this doesn't allow you to pass a size. An example would be passing 2 with the letters abcs would give me all permutations of 2 with those letters. Example: ab,ac,as,bc,bs and so on. If it was 3 then it would be abc,abs,acb,asb and so on.

Jul 13, 2013 IP

Messages:
262