note 70370 added to function.shuffle
| From: | m227 at tlen dot pl | Date: | Fri, 13 Oct 2006 10:22:07 +0000 |
| Subject: | note 70370 added to function.shuffle | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-118488@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.
/** (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;
}
----
Server IP: 195.136.184.34
Probable Submitter: 80.55.213.54
----
Manual Page -- http://www.php.net/manual/en/function.shuffle.php
Edit -- https://master.php.net/note/edit/70370
Del: integrated -- https://master.php.net/note/delete/70370/integrated
Del: useless -- https://master.php.net/note/delete/70370/useless
Del: bad code -- https://master.php.net/note/delete/70370/bad+code
Del: spam -- https://master.php.net/note/delete/70370/spam
Del: non-english -- https://master.php.net/note/delete/70370/non-english
Del: in docs -- https://master.php.net/note/delete/70370/in+docs
Del: other reasons-- https://master.php.net/note/delete/70370
Reject -- https://master.php.net/note/reject/70370
Search -- https://master.php.net/manage/user-notes.php