Generalized Sort
+1
−0
Challenge
We all know and love the generic sort function, right? However, it only sorts based off one criterion - what if we want more? That's where you come in.
Your task is to sort an array based off an arbitrary number of comparison functions c1
, c2
, c3
, etc.; first sort by comparing using c1
, if there is a tie then sort by c2
, if there is still a tie sort by c3
, etc. Output order is undefined if none of the comparison functions breaks the tie.
Example
Here is an example in JavaScript:
function sort(array, ...comparators) {
return array.sort((a, b) =>
comparators.map(c => c(a, b)) // Apply comparisons
.find(r => r != 0) // Find the first non-zero comparison
);
}
Test Cases
Here is a test case, sorting first by last name then by first name.[1]
Christina Johnson
Steward Johnson
Steward White
Steward O'Brian
Steward Smith
Bill Smith
John Johnson
James Smith
Sally Johnson
Christina Meyers
Chris Meyers
Steward Meyers
Bill O'Brian
Zachary Smith
Chris Brown
Zachary O'Brian
Abbey Smith
Zachary Meyers
John Brown
Sally Smith
Zachary Johnson
Chris White
=>
Chris Brown
John Brown
Christina Johnson
John Johnson
Sally Johnson
Steward Johnson
Zachary Johnson
Chris Meyers
Christina Meyers
Steward Meyers
Zachary Meyers
Bill O'Brian
Steward O'Brian
Zachary O'Brian
Abbey Smith
Bill Smith
James Smith
Sally Smith
Steward Smith
Zachary Smith
Chris White
Steward White
This is code-golf, so the entry with the lowest bytes wins!
-
Incidentally, I generated this data with a short script ↩︎
0 comment threads