Skip to content

Instantly share code, notes, and snippets.

@sushiljainam
Created February 18, 2017 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sushiljainam/4ab6ececff86165831b4380463f500ea to your computer and use it in GitHub Desktop.
Save sushiljainam/4ab6ececff86165831b4380463f500ea to your computer and use it in GitHub Desktop.
php code to find rank of a name
function findRankByString($input){
$input = strtolower($input);
if(strlen($input) <= 1){
return 1;
}
$chars = [];
for ($i = 0; $i < strlen($input); $i++) {
array_push($chars, $input[$i]);
};
// print_r($chars);
$sortedChars = copyArray($chars);
for ($i = 1; $i < count($sortedChars); $i++) {
for ($j = $i; $j > 0; $j--) {
if ($sortedChars[$j-1]>$sortedChars[$j]) { // should be lower case
$t = $sortedChars[$j];
$sortedChars[$j] = $sortedChars[$j-1];
$sortedChars[$j-1] = $t;
};
}
};
// print_r($sortedChars);
$output = findPartialByCharsSorted($chars, $sortedChars) + 1;
return $output;
}
function findPartialByCharsSorted($chars, $sortedChars, $combSumInit = 0){
$combSum = $combSumInit;
// print_r($tChar);
// print_r($combSum);
$len = count($sortedChars);
if($len <= 0){
return $combSum;
}
$tChar = $chars[0];
for ($j = 0; $j < $len; $j++) {
// echo "loop1";
$doneChars = [];
for ($i = 0; $i < count($sortedChars); $i++) {
if($tChar == $sortedChars[$i]) {
array_splice($chars, 0, 1);
array_splice($sortedChars, $i, 1);
return findPartialByCharsSorted($chars, $sortedChars, $combSum);
// break;
} else if ( !charInArray($sortedChars[$i], $doneChars)){
$temp = copyArray($sortedChars);
array_splice($temp, $i, 1);
$combSum += permuteOver($temp);
array_push($doneChars, $sortedChars[$i]);
}
}
}
}
function permuteOver($chars){
$n = count($chars);
$freq = new ArrayObject();
$deno = 1;
if($n<=1) {return 1;}
for ($i = 0; $i < count($chars); $i++) {
if (isset($freq[$chars[$i]])) {
$freq[$chars[$i]]++;
} else{
$freq[$chars[$i]] = 1;
}
}
foreach($freq as $key => $value) {
if($freq[$key]>1){
$deno *= factorial($freq[$key]);
}
}
return (factorial($n))/$deno;
}
function charInArray($c, $arr){
for ($i = 0; $i < count($arr); $i++) {
if($c==$arr[$i]){
return true;
}
}
}
function factorial($x) {
if($x==0) {
return 1;
}
return $x * factorial($x-1);
}
function copyArray($a){
$r = [];
for ($i = 0; $i < count($a); $i++) {
array_push($r, $a[$i]);
}
return $r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment