Last active
November 9, 2018 09:00
-
-
Save Gyvastis/520b24b8c7b620ba5629f75f318c90f4 to your computer and use it in GitHub Desktop.
Calculate string/sentance score for score-based sorting. Use case: elasticsearch score-based search.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$alphabeth = strtolower('ABCDEFGHIJKLMNOPQRSTUVWXYZ'); | |
$sentances = [ | |
'Fifa 2018', | |
'Grand Theft Auto V', | |
'Sims 5', | |
'Hitman', | |
'Assasins Creed', | |
'Half-life', | |
'Team Fortress 2' | |
]; | |
function calculate_sentance_score($alphabeth, $sentance, $accuracy = 20) { | |
$overallScore = 0; | |
$weight = 0; | |
$cleanedSentance = preg_replace("/[^$alphabeth]/i", '', $sentance); | |
foreach(str_split($cleanedSentance) as $letter) { | |
$letterScore = stripos($alphabeth, $letter); | |
$letterScore++; | |
$weight++; | |
// exponentially lower the boost the further the letter is | |
$letterBoost = 1 / pow($accuracy, $weight); | |
// var_dump([ $letter, $letterScore * $letterBoost ]); | |
$overallScore += $letterScore * $letterBoost; | |
} | |
return $overallScore; | |
} | |
$sentanceScores = []; | |
foreach($sentances as $sentance) { | |
$sentanceScores[$sentance] = calculate_sentance_score($alphabeth, $sentance); | |
} | |
uasort($sentanceScores, function($scoreA, $scoreB) { | |
return $scoreA > $scoreB; | |
}); | |
var_dump($sentanceScores); |
Author
Gyvastis
commented
Nov 9, 2018
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment