Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Created September 3, 2016 03:51
Show Gist options
  • Save sword-jin/696dc1cebc1582ab0800e04c04f80f58 to your computer and use it in GitHub Desktop.
Save sword-jin/696dc1cebc1582ab0800e04c04f80f58 to your computer and use it in GitHub Desktop.
Collaction starand rank (1224)
<?php
use Illuminate\Support\Collection;
require __dir__ . '/vendor/autoload.php';
Collection::macro('pipe', function ($callback) {
return $callback($this);
});
$scores = [
['score' => 76, 'team' => 'A'],
['score' => 62, 'team' => 'B'],
['score' => 82, 'team' => 'C'],
['score' => 86, 'team' => 'D'],
['score' => 91, 'team' => 'E'],
['score' => 67, 'team' => 'F'],
['score' => 67, 'team' => 'G'],
['score' => 82, 'team' => 'H'],
];
function rank_scores ($scores) {
return collect($scores)
->pipe(function ($scores) {
return assign_initial_rankings($scores);
})
->pipe(function ($rankedScores) {
return adjust_rankings_for_ties($rankedScores);
});
}
function assign_initial_rankings($scores) {
return $scores->sortByDesc('score')
->zip(range(1, $scores->count()))
->map(function ($scoreAndRank) {
list($score, $rank) = $scoreAndRank;
return array_merge($score, [
'rank' => $rank
]);
});
}
function adjust_rankings_for_ties($scores) {
return $scores->groupBy('score')
->map(function ($tiedScores) {
return apply_min_rank($tiedScores);
})
->collapse()
->sortBy('rank');
}
function apply_min_rank($tiedScores) {
$lowestRank = $tiedScores->pluck('rank')->min();
return $tiedScores->map(function ($rankedScore) use ($lowestRank) {
return array_merge($rankedScore, [
'rank' => $lowestRank
]);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment