Jump to content

Array Permutation


jeeva

Recommended Posts

Dear friends,

 

I am having problems as I would like to take values out of an array

 

Example

$name = array (a,b,c);

 

and the output should be like

 

eg

a,b,c

a,b

a,c

b,c

 

Does anyone know how to do this?

 

Thanks

Jeeva

Link to comment
Share on other sites

try

<?php
$a = array(1,2,3,4);
function my_permut($a){
if (count($a) == 1)return array($a, array());
$out = array();
foreach ($a as $k => $v){
	unset($a[$k]);
	$b = my_permut($a);
	$out = array_merge(my_merge($v, $b), $out);
	$out = array_merge($out, $b);
	break;
}
return $out;
}
function my_merge($a, $b){
if (count($b) == 0) return array($a);
foreach ($b as $k => $v){
	array_unshift($v, $a);
	$b[$k] = $v;
}
return $b;
}
$b = my_permut($a);
print_r($b);
?>

Link to comment
Share on other sites

What are you trying to do? List all possible combinations?

 

Of course this is going to take a long time. There are n^n possibilities. The number of possibilities is going to grow pretty rapidly as n increases.

 

However sasa' code does not return all possible values. For example, proding two numbers, 1 and 2, it would not return 2,1 as a combination. The code provided appears to run relatively quickly for 12 numbers here.

Link to comment
Share on other sites

thanks GingerRobot

 

sasa code is  right for me. that is wt i expected actually ..

here 1,2 is equal to 2,1

 

By using this i want to search candidate profile..

for example,

 

if user will give keyword like a,b,c

i want to search all possibilities like

1. a and b and c

2. a and b

3. b and c

4. a and c

and a,b,c

 

 

Thanks

Jeeva

Link to comment
Share on other sites

They are right Jeeva, but I don't see the problem, surely you'll never have 10 values for n anyway, because very few people enter more than 3-5 words when performing a search, so there shouldn't be too much trouble...

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.