Jump to content

Order by pair comparisons: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|J}}: make quicksort implementation be general (taking comparison function as an argument))
m (syntax highlighting fixup automation)
Line 32:
{{trans|Python: Sort with custom comparator}}
 
<langsyntaxhighlight lang="11l">F user_cmp(String a, b)
R Int(input(‘IS #6 <, ==, or > #6 answer -1, 0 or 1:’.format(a, b)))
 
V items = ‘violet red green indigo blue yellow orange’.split(‘ ’)
V ans = sorted(items, key' cmp_to_key(user_cmp))
print("\n"ans.join(‘ ’))</langsyntaxhighlight>
 
{{out}}
Line 70:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE PTR="CARD"
 
PROC PrintArray(PTR ARRAY a BYTE size)
Line 137:
PutE() Print("Sorted array: ")
PrintArray(arr,COUNT)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Order_by_pair_comparisons.png Screenshot from Atari 8-bit computer]
Line 168:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">lst: ["violet" "red" "green" "indigo" "blue" "yellow" "orange"]
count: 0
 
Line 187:
 
print ""
print ["sorted =>" sortedLst]</langsyntaxhighlight>
 
{{out}}
Line 205:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">data := ["Violet", "Red", "Green", "Indigo", "Blue", "Yellow", "Orange"]
result := [], num := 0, Questions :=""
 
Line 234:
output .= color ", "
MsgBox % Questions "`nSorted Output :`n" Trim(output, ", ")
return</langsyntaxhighlight>
 
{{out}}
Line 256:
=={{header|C}}==
Using qsort; not very efficient
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <stdlib.h>
Line 288:
printOrder(items, sizeof(items)/sizeof(*items));
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 315:
=={{header|C++}}==
===C++: Binary search insertion sort===
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <vector>
Line 361:
PrintOrder(sortedItems);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 388:
 
===C++: STL sort with custom comparator===
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <vector>
Line 421:
PrintOrder(items);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 442:
 
=={{header|Commodore BASIC}}==
<langsyntaxhighlight lang="basic">100 REM SORT BY COMPARISON
110 DIM IN$(6), OU$(6)
120 FOR I=0 TO 6:READ IN$(I): NEXT I
Line 474:
410 FOR Q=0 TO N-2:PRINT OU$(Q)",";:NEXT Q
420 PRINT OU$(N-1)")"
430 RETURN</langsyntaxhighlight>
{{Out}}
<pre>
Line 494:
=={{header|F_Sharp|F#}}==
This task uses [https://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection#F.23 Factorial base numbers indexing permutations of a collection (F#)]
<langsyntaxhighlight lang="fsharp">
// Order by pair comparisons. Nigel Galloway: April 23rd., 2021
let clrs=let n=System.Random() in lN2p [|for g in 7..-1..2->n.Next(g)|] [|"Red";"Orange";"Yellow";"Green";"Blue";"Indigo";"Violet"|]
let rec fG n g=printfn "Is %s less than %s" n g; match System.Console.ReadLine() with "Yes"-> -1|"No"->1 |_->printfn "Enter Yes or No"; fG n g
let mutable z=0 in printfn "%A sorted to %A using %d questions" clrs (clrs|>Array.sortWith(fun n g->z<-z+1; fG n g)) z
</syntaxhighlight>
</lang>
{{out}}
Possible interaction:
Line 549:
Asking the user for an ordering specifier inside a custom comparator:
{{works with|Factor|0.99 2021-02-05}}
<langsyntaxhighlight lang="factor">USING: formatting io kernel math.order prettyprint qw sorting ;
 
qw{ violet red green indigo blue yellow orange }
[ "Is %s > %s? (y/n) " printf readln "y" = +gt+ +lt+ ? ] sort .</langsyntaxhighlight>
{{out}}
<pre>
Line 573:
=={{header|FreeBASIC}}==
{{trans|Commodore BASIC}}
<langsyntaxhighlight lang="freebasic">
Dim Shared As Byte r, n = 1
Dim Shared As String IN1, OU1
Line 618:
PrintOrder
Sleep
</syntaxhighlight>
</lang>
 
 
=={{header|Go}}==
===Go: Binary search insertion sort===
<langsyntaxhighlight lang="go">package main
import (
Line 659:
}
fmt.Println(sortedItems)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 686:
 
===Go: Standard sort with custom comparator===
<langsyntaxhighlight lang="go">package main
import (
Line 712:
sort.Sort(items)
fmt.Println(items)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 733:
Injection of interaction with user is not straight-forward in pure functional language. In Haskell we use monads in order to abstract the computation flow and side effects. Fortunately the monadlist library [[https://hackage.haskell.org/package/monadlist]] contains monadic variants of most popular list operations so that it becomes easy to implement our favorite sorting algorithms.
 
<langsyntaxhighlight lang="haskell">import Control.Monad
import Control.Monad.ListM (sortByM, insertByM, partitionM, minimumByM)
import Data.Bool (bool)
Line 754:
go (h:t) = do (l, g) <- partitionM (fmap (LT /=) . cmp h) t
go l <+> pure [h] <+> go g
(<+>) = liftM2 (++)</langsyntaxhighlight>
 
Now we can sort lists with effects. For example, we may count number of comparisons, using writer monad:
Line 780:
We are ready to ask user to compare entries for us:
<langsyntaxhighlight lang="haskell">ask a b = do
putStr $ show a ++ " ≤ " ++ show b ++ " ? [y/n] "
bool GT LT . ("y" ==) <$> getLine
 
colors = ["Violet", "Red", "Green", "Indigo", "Blue", "Yellow", "Orange"]</langsyntaxhighlight>
 
<pre>*Main> isortM ask colors
Line 841:
It seems that insertion sort with 13 comparisons is the best one, and tree sort which needed 17 questions is the worst. But efficiency of sorting depends on the order of given list. Simple statistics could be made to compare these three methods for all possible permutations of seven elements.
 
<langsyntaxhighlight lang="haskell">test method = do
mapM_ showHist $ hist res
putStrLn $ "Median number of comparisons: " ++ show (median res)
Line 855:
line = show n ++ "\t" ++ bar ++ " " ++ show perc ++ "%"
bar = replicate (max perc 1) '*'
perc = (100 * l) `div` product [1..7]</langsyntaxhighlight>
 
Comparing these three methods gives that for random inputs tree sort is the best choice.
Line 911:
 
=={{header|J}}==
Implementation (here we assume that ordering is transitive):<langsyntaxhighlight Jlang="j">require'general/misc/prompt'
sel=: {{ u#[ }}
 
Line 941:
LT=: <:%=i.#items
askless quicksort y
}}</langsyntaxhighlight>
 
Task example:<langsyntaxhighlight Jlang="j"> asksort&.;:' violet red green indigo blue yellow orange'
Is indigo less than violet? yes
Is indigo less than red? no
Line 956:
Is green less than blue? yes
Is red less than orange? yes
red orange yellow green blue indigo violet</langsyntaxhighlight>
 
=={{header|Java}}==
===Java: Binary search insertion sort===
<langsyntaxhighlight lang="java">import java.util.*;
 
public class SortComp1 {
Line 984:
System.out.println(sortedItems);
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,011:
 
===Java: Standard sort with custom comparator===
<langsyntaxhighlight lang="java">import java.util.*;
 
public class OrderByPair {
Line 1,026:
System.out.println(items);
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,053:
In order for a jq program to interact with a user, prompts must be directed to stderr,
which currently means that the prompt string will be printed with quotation marks.
<langsyntaxhighlight lang="jq">def inputOption($prompt; $options):
def r:
$prompt | stderr
Line 1,085:
| order as $ordered
| ("\nThe colors of the rainbow, in sorted order, are:",
$ordered )</langsyntaxhighlight>
 
'''Recommended Invocation Options''': -nRrc
Line 1,124:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">const nrequests = [0]
const ordering = Dict("violet" => 7, "red" => 1, "green" => 4, "indigo" => 6, "blue" => 5,
"yellow" => 3, "orange" => 2)
Line 1,164:
println("Unsorted: $words")
println("Sorted: $(orderbypair!(words)). Total requests: $(nrequests[1]).")
</langsyntaxhighlight>{{out}}
<pre>
Is violet greater than indigo? (Y/N) => y
Line 1,184:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">colors = { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }
print("unsorted: " .. table.concat(colors," "))
known, notyn, nc, nq = {}, {n="y",y="n"}, 0, 0
Line 1,199:
end)
print("sorted: " .. table.concat(colors," "))
print("(" .. nq .. " questions needed to resolve " .. nc .. " comparisons)")</langsyntaxhighlight>
{{out}}
<pre>unsorted: violet red green indigo blue yellow orange
Line 1,220:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[HumanOrderCheck]
HumanOrderCheck[opt1_,opt2_]:=ChoiceDialog[Row@{"Is {",opt1,", ", opt2, "} ordered?"},{"Yes"->True,"No"->False}]
Sort[{"violet","red","green","indigo","blue","yellow","orange"},HumanOrderCheck]</langsyntaxhighlight>
{{out}}
After some Yes/No clicks you should get:
Line 1,229:
=={{header|Nim}}==
Using a list filled by binary insertion and a custom comparison function.
<langsyntaxhighlight Nimlang="nim">import algorithm, strformat, strutils
 
let list = ["violet", "red", "green", "indigo", "blue", "yellow", "orange"]
Line 1,251:
sortedList.insert(elem, sortedList.upperBound(elem, comp))
 
echo "Sorted list: ", sortedList.join(", ")</langsyntaxhighlight>
 
{{out}}
Line 1,273:
 
List:
<langsyntaxhighlight lang="ocaml">let () =
let count = ref 0 in
let mycmp s1 s2 = (
Line 1,283:
let sorted = List.sort mycmp items in
List.iter (Printf.printf "%s ") sorted;
print_newline ()</langsyntaxhighlight>
{{out}}
<pre>
Line 1,303:
 
Array:
<langsyntaxhighlight lang="ocaml">let () =
let count = ref 0 in
let mycmp s1 s2 = (
Line 1,313:
Array.sort mycmp items;
Array.iter (Printf.printf "%s ") items;
print_newline ()</langsyntaxhighlight>
{{out}}
<pre>
Line 1,339:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Order_by_pair_comparisons
Line 1,354:
 
my @sorted = sort ask qw( violet red green indigo blue yellow orange );
print "sorted: @sorted\n";</langsyntaxhighlight>
{{out}}
<pre>
Line 1,379:
I picked an initial ordering that requires a fairly easy to remember set of answers: 4Y then alternate.<br>
The builtin sort(s) use an initial gap of 10%, ultimately balancing #comparisons against cache hits, which leads to a wider range of #questions, as said best case 6, worst case 21. A better match to the narrower range of Python (I think 10..14) could probably be made using a copy of custom_sort (it is only 52 lines) with an initial 50% gap.
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">qn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">ask</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
Line 1,390:
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">custom_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ask</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"violet orange red yellow green blue indigo"</span><span style="color: #0000FF;">))</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,411:
Uses binary search to insert successive items into a growing ordered list. Comparisons are asked for.
 
<langsyntaxhighlight lang="python">def _insort_right(a, x, q):
"""
Insert item x in list a, and keep it sorted assuming a is sorted.
Line 1,436:
items = 'violet red green indigo blue yellow orange'.split()
ans, questions = order(items)
print('\n' + ' '.join(ans))</langsyntaxhighlight>
 
{{out}}
Line 1,470:
This uses a custom comparator together with [https://docs.python.org/3/library/functools.html?highlight=cmp_to_key#functools.cmp_to_key functools.cmp_to_key] to sort the previous order in fourteen questions.
 
<langsyntaxhighlight lang="python">from functools import cmp_to_key
 
def user_cmp(a, b):
Line 1,478:
items = 'violet red green indigo blue yellow orange'.split()
ans = sorted(items, key=cmp_to_key(user_cmp))
print('\n' + ' '.join(ans))</langsyntaxhighlight>
 
{{out}}
Line 1,515:
<code>sortwith</code> sorts by insertion sort by default, of by merge sort falling back to insertion sort for nests of fewer than 16 items if the Quackery extensions are loaded. In either instance, as this is sorting a nest of seven items, it will be by insertion sort.
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "Is " swap join
$ " before " join
swap join
Line 1,527:
dup witheach [ echo$ sp ] cr cr
sortwith askuser cr
witheach [ echo$ sp ] cr</langsyntaxhighlight>
 
{{out}}
Line 1,556:
Since the calls to the comparator are minimized, and the info that the user provides is analogous to the required return values of the comparator, we just need to embed the prompt directly in the comparator.
 
<syntaxhighlight lang="raku" perl6line>my $ask_count = 0;
sub by_asking ( $a, $b ) {
$ask_count++;
Line 1,577:
die if @sorted».substr(0,1).join ne 'roygbiv';
my $expected_ask_count = @colors.elems * log(@colors.elems);
warn "Too many questions? ({:$ask_count} > {:$expected_ask_count})" if $ask_count > $expected_ask_count;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,602:
 
Also note that lists in REXX start with unity, not zero.
<langsyntaxhighlight lang="rexx">/*REXX pgm orders some items based on (correct) answers from a carbon─based life form. */
colors= 'violet red green indigo blue yellow orange'
q= 0; #= 0; $=
Line 1,626:
else lo= mid + 1
end /*q*/
$= subword($, 1, lo) x subword($, lo+1); return q</langsyntaxhighlight>
{{out|output|text=&nbsp; (only showing the results and eliding the querying/answering):}}
<pre>
Line 1,648:
=={{header|Ruby}}==
===Ruby: Binary search insertion sort===
<langsyntaxhighlight lang="ruby">items = ["violet", "red", "green", "indigo", "blue", "yellow", "orange"]
count = 0
sortedItems = []
Line 1,660:
sortedItems.insert(spotToInsert, item)
}
p sortedItems</langsyntaxhighlight>
{{out}}
<pre>
Line 1,687:
 
===Ruby: Standard sort with custom comparator===
<langsyntaxhighlight lang="ruby">items = ["violet", "red", "green", "indigo", "blue", "yellow", "orange"]
count = 0
p items.sort {|a, b|
Line 1,693:
print "(#{count}) Is #{a} <, =, or > #{b}. Answer -1, 0, or 1: "
gets.to_i
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,722:
{{libheader|Wren-ioutil}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/ioutil" for Input
import "/fmt" for Fmt
 
Line 1,757:
var ordered = order.call(items)
System.print("\nThe colors of the rainbow, in sorted order, are:")
System.print(ordered)</langsyntaxhighlight>
 
{{out}}
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.