Skip to content

Instantly share code, notes, and snippets.

@Gyvastis
Last active November 9, 2018 09:00
Show Gist options
  • Save Gyvastis/520b24b8c7b620ba5629f75f318c90f4 to your computer and use it in GitHub Desktop.
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.
<?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);
@Gyvastis
Copy link
Author

Gyvastis commented Nov 9, 2018

array(10) {
  ["Assasins Creed"]=>
  float(0.09988733981233)
  ["Fifa 2018"]=>
  float(0.32325625)
  ["Grand Theft Auto V"]=>
  float(0.39521406895899)
  ["Half-life"]=>
  float(0.40404139550781)
  ["Hitman"]=>
  float(0.42508178125)
  ["Player Unknown's Battlegrounds"]=>
  float(0.83028311072606)
  ["Sims 5"]=>
  float(0.97424375)
  ["Team Fortress 2"]=>
  float(1.0127083742545)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment