note 70370 modified in function.shuffle by danbrown
| From: | danbrown@php.net | Date: | Fri, 25 Jul 2008 17:49:02 +0000 |
| Subject: | note 70370 modified in function.shuffle by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142723@lists.php.net to get a copy of this message | ||
here come my three pennies about permutations. I did function below to work with word anagrams, it
works flawlessly, however may be seen as a slow one.
<?php
/** (c) on LGPL license 2006.10 michal@glebowski.pl */
function fact($int){
if($int<2)return 1;
for($f=2;$int-1>1;$f*=$int--);
return $f;
}
/** @return string string $s with $n-th character cut */
function del($s, $n) {
return substr($s, 0, $n).substr($s, $n+1);
}
/**
* @param $s string word to permute
* @param $n int n-th permutation
* @return string n-th permutation (out of strlen(string)!)
*/
function perm($s, $n = null) {
if ($n === null) return perms($s);
$r = '';
$l = strlen($s);
while ($l--) {
$f = fact($l);
$p = floor($n/$f);
$r.= $s{$p};
$s = del($s, $p);
$n-= $p*$f;
}
$r.=$s;
return $r;
}
/** @return array array of all permutations */
function perms($s) {
$p = array();
for ($i=0;$i<fact(strlen($s));$i++) $p[] = perm($s, $i);
return $p;
}
?>
--was--
here come my three pennies about permutations. I did function below to work with word anagrams, it
works flawlessly, however may be seen as a slow one.
/** (c) on LGPL license 2006.10 michal@glebowski.pl */
function fact($int){
if($int<2)return 1;
for($f=2;$int-1>1;$f*=$int--);
return $f;
}
/** @return string string $s with $n-th character cut */
function del($s, $n) {
return substr($s, 0, $n).substr($s, $n+1);
}
/**
* @param $s string word to permute
* @param $n int n-th permutation
* @return string n-th permutation (out of strlen(string)!)
*/
function perm($s, $n = null) {
if ($n === null) return perms($s);
$r = '';
$l = strlen($s);
while ($l--) {
$f = fact($l);
$p = floor($n/$f);
$r.= $s{$p};
$s = del($s, $p);
$n-= $p*$f;
}
$r.=$s;
return $r;
}
/** @return array array of all permutations */
function perms($s) {
$p = array();
for ($i=0;$i<fact(strlen($s));$i++) $p[] = perm($s, $i);
return $p;
}
http://php.net/manual/en/function.shuffle.php