Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
3
Task/Order-by-pair-comparisons/00-META.yaml
Normal file
3
Task/Order-by-pair-comparisons/00-META.yaml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Order_by_pair_comparisons
|
||||
note: Sorting Algorithms
|
||||
29
Task/Order-by-pair-comparisons/00-TASK.txt
Normal file
29
Task/Order-by-pair-comparisons/00-TASK.txt
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
{{Sorting Algorithm}}
|
||||
[[Category:Sorting]]
|
||||
|
||||
Assume we have a set of items that can be sorted into an order by the user.
|
||||
|
||||
The user is presented with pairs of items from the set in ''no'' order,
|
||||
the user states which item
|
||||
is less than, equal to, or greater than the other (with respect to their
|
||||
relative positions if fully ordered).
|
||||
|
||||
Write a function that given items that the user can order, '''asks the user''' to
|
||||
give the result of ''comparing two items at a time'' and uses the comparison results
|
||||
to eventually return the items in order.
|
||||
|
||||
Try and minimise the comparisons the user is asked for.
|
||||
|
||||
Show on this page, the function ordering the colours of the rainbow:
|
||||
violet red green indigo blue yellow orange
|
||||
|
||||
The correct ordering being:
|
||||
red orange yellow green blue indigo violet
|
||||
|
||||
Note:
|
||||
* Asking for/receiving user comparisons is a part of the task.
|
||||
* Code ''inputs'' should not assume an ordering.
|
||||
* The seven colours can form twenty-one different pairs.
|
||||
* A routine that does not ask the user "too many" comparison questions should be used.
|
||||
<br><br>
|
||||
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
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(‘ ’))
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
DEFINE PTR="CARD"
|
||||
|
||||
PROC PrintArray(PTR ARRAY a BYTE size)
|
||||
BYTE i
|
||||
|
||||
Put('[)
|
||||
FOR i=0 TO size-1
|
||||
DO
|
||||
IF i>0 THEN Put(' ) FI
|
||||
Print(a(i))
|
||||
OD
|
||||
Put(']) PutE()
|
||||
RETURN
|
||||
|
||||
BYTE FUNC IsBefore(CHAR ARRAY a,b)
|
||||
DEFINE NO_KEY="255"
|
||||
DEFINE KEY_Y="43"
|
||||
DEFINE KEY_N="35"
|
||||
BYTE CH=$02FC ;Internal hardware value for last key pressed
|
||||
BYTE k
|
||||
|
||||
PrintF("Is %S before %S (y/n)? ",a,b)
|
||||
CH=NO_KEY ;Flush the keyboard
|
||||
DO
|
||||
k=CH
|
||||
UNTIL k=KEY_Y OR k=KEY_N
|
||||
OD
|
||||
CH=NO_KEY ;Flush the keyboard
|
||||
IF k=KEY_Y THEN
|
||||
PrintE("yes")
|
||||
RETURN (1)
|
||||
FI
|
||||
PrintE("no")
|
||||
RETURN (0)
|
||||
|
||||
PROC InteractiveInsertionSort(PTR ARRAY a BYTE size)
|
||||
INT i,j
|
||||
PTR value
|
||||
|
||||
FOR i=1 TO size-1
|
||||
DO
|
||||
value=a(i)
|
||||
j=i-1
|
||||
WHILE j>=0 AND IsBefore(value,a(j))=1
|
||||
DO
|
||||
a(j+1)=a(j)
|
||||
j==-1
|
||||
OD
|
||||
a(j+1)=value
|
||||
OD
|
||||
RETURN
|
||||
|
||||
PROC Main()
|
||||
DEFINE COUNT="7"
|
||||
PTR ARRAY arr(COUNT)
|
||||
|
||||
arr(0)="violet" arr(1)="red"
|
||||
arr(2)="green" arr(3)="indigo"
|
||||
arr(4)="blue" arr(5)="yellow"
|
||||
arr(6)="orange"
|
||||
|
||||
Print("Shuffled array: ")
|
||||
PrintArray(arr,COUNT) PutE()
|
||||
|
||||
InteractiveInsertionSort(arr,COUNT)
|
||||
PutE() Print("Sorted array: ")
|
||||
PrintArray(arr,COUNT)
|
||||
RETURN
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
lst: ["violet" "red" "green" "indigo" "blue" "yellow" "orange"]
|
||||
count: 0
|
||||
|
||||
findSpot: function [l,e][
|
||||
if empty? l -> return 0
|
||||
|
||||
loop.with:'i l 'item [
|
||||
answer: input ~"Is |item| greater than |e| [y/n]? "
|
||||
if answer="y" -> return i
|
||||
]
|
||||
return dec size l
|
||||
]
|
||||
|
||||
sortedLst: new []
|
||||
|
||||
loop lst 'element ->
|
||||
insert 'sortedLst findSpot sortedLst element element
|
||||
|
||||
print ""
|
||||
print ["sorted =>" sortedLst]
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
data := ["Violet", "Red", "Green", "Indigo", "Blue", "Yellow", "Orange"]
|
||||
result := [], num := 0, Questions :=""
|
||||
|
||||
for i, Color1 in data{
|
||||
found :=false
|
||||
if !result.count(){
|
||||
result.Push(Color1)
|
||||
continue
|
||||
}
|
||||
|
||||
for j, Color2 in result {
|
||||
if (color1 = color2)
|
||||
continue
|
||||
MsgBox, 262180,, % (Q := "Q" ++num " is " Color1 " > " Color2 "?")
|
||||
ifMsgBox, Yes
|
||||
Questions .= Q "`t`tYES`n"
|
||||
else {
|
||||
Questions .= Q "`t`tNO`n"
|
||||
result.InsertAt(j, Color1)
|
||||
found := true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found
|
||||
result.Push(Color1)
|
||||
}
|
||||
for i, color in result
|
||||
output .= color ", "
|
||||
MsgBox % Questions "`nSorted Output :`n" Trim(output, ", ")
|
||||
return
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
bool InteractiveCompare(const string& s1, const string& s2)
|
||||
{
|
||||
if(s1 == s2) return false; // don't ask to compare items that are the same
|
||||
static int count = 0;
|
||||
string response;
|
||||
cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
|
||||
getline(cin, response);
|
||||
return !response.empty() && response.front() == 'y';
|
||||
}
|
||||
|
||||
void PrintOrder(const vector<string>& items)
|
||||
{
|
||||
cout << "{ ";
|
||||
for(auto& item : items) cout << item << " ";
|
||||
cout << "}\n";
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
const vector<string> items
|
||||
{
|
||||
"violet", "red", "green", "indigo", "blue", "yellow", "orange"
|
||||
};
|
||||
|
||||
vector<string> sortedItems;
|
||||
|
||||
// Use a binary insertion sort to order the items. It should ask for
|
||||
// close to the minimum number of questions required
|
||||
for(auto& item : items)
|
||||
{
|
||||
cout << "Inserting '" << item << "' into ";
|
||||
PrintOrder(sortedItems);
|
||||
// lower_bound performs the binary search using InteractiveCompare to
|
||||
// rank the items
|
||||
auto spotToInsert = lower_bound(sortedItems.begin(),
|
||||
sortedItems.end(), item, InteractiveCompare);
|
||||
sortedItems.insert(spotToInsert, item);
|
||||
}
|
||||
PrintOrder(sortedItems);
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
bool InteractiveCompare(const string& s1, const string& s2)
|
||||
{
|
||||
if(s1 == s2) return false; // don't ask to compare items that are the same
|
||||
static int count = 0;
|
||||
string response;
|
||||
cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
|
||||
getline(cin, response);
|
||||
return !response.empty() && response.front() == 'y';
|
||||
}
|
||||
|
||||
void PrintOrder(const vector<string>& items)
|
||||
{
|
||||
cout << "{ ";
|
||||
for(auto& item : items) cout << item << " ";
|
||||
cout << "}\n";
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<string> items
|
||||
{
|
||||
"violet", "red", "green", "indigo", "blue", "yellow", "orange"
|
||||
};
|
||||
|
||||
sort(items.begin(), items.end(), InteractiveCompare);
|
||||
PrintOrder(items);
|
||||
return 0;
|
||||
}
|
||||
33
Task/Order-by-pair-comparisons/C/order-by-pair-comparisons.c
Normal file
33
Task/Order-by-pair-comparisons/C/order-by-pair-comparisons.c
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int interactiveCompare(const void *x1, const void *x2)
|
||||
{
|
||||
const char *s1 = *(const char * const *)x1;
|
||||
const char *s2 = *(const char * const *)x2;
|
||||
static int count = 0;
|
||||
printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2);
|
||||
int response;
|
||||
scanf("%d", &response);
|
||||
return response;
|
||||
}
|
||||
|
||||
void printOrder(const char *items[], int len)
|
||||
{
|
||||
printf("{ ");
|
||||
for (int i = 0; i < len; ++i) printf("%s ", items[i]);
|
||||
printf("}\n");
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
const char *items[] =
|
||||
{
|
||||
"violet", "red", "green", "indigo", "blue", "yellow", "orange"
|
||||
};
|
||||
|
||||
qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);
|
||||
printOrder(items, sizeof(items)/sizeof(*items));
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
100 REM SORT BY COMPARISON
|
||||
110 DIM IN$(6), OU$(6)
|
||||
120 FOR I=0 TO 6:READ IN$(I): NEXT I
|
||||
130 DATA VIOLET,RED,GREEN,INDIGO,BLUE,YELLOW,ORANGE
|
||||
140 OU$(0)=IN$(0):N=1
|
||||
150 FOR I=1 TO 6
|
||||
160 : IN$=IN$(I)
|
||||
180 : GOSUB 390
|
||||
190 : FOR J=0 TO N-1
|
||||
200 : OU$ = OU$(J)
|
||||
210 : GOSUB 340
|
||||
220 : IF R>=0 THEN 280
|
||||
230 : FOR K=N TO J+1 STEP -1
|
||||
240 : OU$(K) = OU$(K-1)
|
||||
250 : NEXT K
|
||||
260 : OU$(J) = IN$
|
||||
270 : GOTO 300
|
||||
280 : NEXT J
|
||||
290 : OU$(N) = IN$
|
||||
300 : N=N+1
|
||||
310 NEXT I
|
||||
320 GOSUB 390
|
||||
330 END
|
||||
340 PRINT "IS "IN$" < "OU$"? (Y/N)";
|
||||
350 GET K$: IF K$<>"Y" AND K$<>"N" THEN 350
|
||||
360 PRINT K$
|
||||
370 R = K$="Y"
|
||||
380 RETURN
|
||||
390 PRINT "(";
|
||||
400 IF N=1 THEN 420
|
||||
410 FOR Q=0 TO N-2:PRINT OU$(Q)",";:NEXT Q
|
||||
420 PRINT OU$(N-1)")"
|
||||
430 RETURN
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
// 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
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
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 .
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
Dim Shared As Byte r, n = 1
|
||||
Dim Shared As String IN1, OU1
|
||||
Dim Shared As String IN(6), OU(6)
|
||||
Dim As Byte i, j, k
|
||||
For i = 0 To 6 : Read IN(i) : Next i
|
||||
Data "violet", "red", "green", "indigo", "blue", "yellow", "orange"
|
||||
OU(0) = IN(0)
|
||||
|
||||
Sub PrintOrder
|
||||
Print : Print "{";
|
||||
If n = 1 Then Print OU(n-1);")" : Exit Sub
|
||||
For q As Byte = 0 To n-2
|
||||
Print OU(q);", ";
|
||||
Next q
|
||||
Print OU(n-1);"}"
|
||||
End Sub
|
||||
|
||||
Sub InteractiveCompare
|
||||
Dim As String*1 T
|
||||
Print "Es "; IN1; " < "; OU1; "? (S/N) ";
|
||||
Do: T = Inkey$: Loop Until T <> ""
|
||||
If Instr("snSN", T) Then Print Ucase(T)
|
||||
r = T = "S"
|
||||
End Sub
|
||||
|
||||
For i = 1 To 6
|
||||
IN1 = IN(i)
|
||||
For j = 0 To n-1
|
||||
OU1 = OU(j)
|
||||
InteractiveCompare
|
||||
If r < 0 Then
|
||||
For k = n To j+1 Step -1
|
||||
OU(k) = OU(k-1)
|
||||
Next k
|
||||
OU(j) = IN1
|
||||
n += 1
|
||||
Exit For, For
|
||||
End If
|
||||
Next j
|
||||
OU(n) = IN1
|
||||
n += 1
|
||||
Next i
|
||||
PrintOrder
|
||||
Sleep
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var count int = 0
|
||||
|
||||
func interactiveCompare(s1, s2 string) bool {
|
||||
count++
|
||||
fmt.Printf("(%d) Is %s < %s? ", count, s1, s2)
|
||||
var response string
|
||||
_, err := fmt.Scanln(&response)
|
||||
return err == nil && strings.HasPrefix(response, "y")
|
||||
}
|
||||
|
||||
func main() {
|
||||
items := []string{"violet", "red", "green", "indigo", "blue", "yellow", "orange"}
|
||||
|
||||
var sortedItems []string
|
||||
|
||||
// Use a binary insertion sort to order the items. It should ask for
|
||||
// close to the minimum number of questions required
|
||||
for _, item := range items {
|
||||
fmt.Printf("Inserting '%s' into %s\n", item, sortedItems)
|
||||
// sort.Search performs the binary search using interactiveCompare to
|
||||
// rank the items
|
||||
spotToInsert := sort.Search(len(sortedItems), func(i int) bool {
|
||||
return interactiveCompare(item, sortedItems[i])
|
||||
})
|
||||
sortedItems = append(sortedItems[:spotToInsert],
|
||||
append([]string{item}, sortedItems[spotToInsert:]...)...)
|
||||
}
|
||||
fmt.Println(sortedItems)
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var count int = 0
|
||||
|
||||
type sortable []string
|
||||
func (s sortable) Len() int { return len(s) }
|
||||
func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
func (s sortable) Less(i, j int) bool {
|
||||
s1, s2 := s[i], s[j]
|
||||
count++
|
||||
fmt.Printf("(%d) Is %s < %s? ", count, s1, s2)
|
||||
var response string
|
||||
_, err := fmt.Scanln(&response)
|
||||
return err == nil && strings.HasPrefix(response, "y")
|
||||
}
|
||||
|
||||
func main() {
|
||||
items := sortable{"violet", "red", "green", "indigo", "blue", "yellow", "orange"}
|
||||
sort.Sort(items)
|
||||
fmt.Println(items)
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import Control.Monad
|
||||
import Control.Monad.ListM (sortByM, insertByM, partitionM, minimumByM)
|
||||
import Data.Bool (bool)
|
||||
import Data.Monoid
|
||||
import Data.List
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
isortM, msortM, tsortM :: Monad m => (a -> a -> m Ordering) -> [a] -> m [a]
|
||||
|
||||
-- merge sort from the Control.Monad.ListM library
|
||||
msortM = sortByM
|
||||
|
||||
-- insertion sort
|
||||
isortM cmp = foldM (flip (insertByM cmp)) []
|
||||
|
||||
-- tree sort aka qsort (which is not)
|
||||
tsortM cmp = go
|
||||
where
|
||||
go [] = pure []
|
||||
go (h:t) = do (l, g) <- partitionM (fmap (LT /=) . cmp h) t
|
||||
go l <+> pure [h] <+> go g
|
||||
(<+>) = liftM2 (++)
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
ask a b = do
|
||||
putStr $ show a ++ " ≤ " ++ show b ++ " ? [y/n] "
|
||||
bool GT LT . ("y" ==) <$> getLine
|
||||
|
||||
colors = ["Violet", "Red", "Green", "Indigo", "Blue", "Yellow", "Orange"]
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
test method = do
|
||||
mapM_ showHist $ hist res
|
||||
putStrLn $ "Median number of comparisons: " ++ show (median res)
|
||||
putStrLn $ "Mean number of comparisons: " ++ show (mean res)
|
||||
where
|
||||
res = getSum . fst . method cmp <$> permutations [1..7]
|
||||
cmp a b = (Sum 1, compare a b)
|
||||
median lst = sort lst !! (length lst `div` 2)
|
||||
mean lst = sum (fromIntegral <$> lst) / genericLength lst
|
||||
hist lst = (\x -> (head x, length x)) <$> group (sort lst)
|
||||
showHist (n, l) = putStrLn line
|
||||
where
|
||||
line = show n ++ "\t" ++ bar ++ " " ++ show perc ++ "%"
|
||||
bar = replicate (max perc 1) '*'
|
||||
perc = (100 * l) `div` product [1..7]
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
require'general/misc/prompt'
|
||||
sel=: {{ u#[ }}
|
||||
|
||||
quicksort=: {{
|
||||
if. 1 >: #y do. y
|
||||
else.
|
||||
(u quicksort y u sel e),(y =sel e),u quicksort y u~ sel e=.y{~?#y
|
||||
end.
|
||||
}}
|
||||
|
||||
ptc=: {{
|
||||
t=. (+. +./ .*.~)^:_ y=1
|
||||
j=. I.,t+.|:t
|
||||
($y)$(j{,t) j} ,y
|
||||
}}
|
||||
|
||||
askless=: {{
|
||||
coord=. x ,&(items&i.) y
|
||||
lt=. LT {~<coord
|
||||
if. 1<lt do.
|
||||
lt=. 'y' e. tolower prompt 'Is ',(":;x),' less than ',(":;y),'? '
|
||||
LT=: ptc (lt,-.lt) (coord;|.coord)} LT
|
||||
end.
|
||||
lt
|
||||
}}"0
|
||||
|
||||
asksort=: {{
|
||||
items=: ~.y
|
||||
LT=: <:%=i.#items
|
||||
askless quicksort y
|
||||
}}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
asksort&.;:' violet red green indigo blue yellow orange'
|
||||
Is indigo less than violet? yes
|
||||
Is indigo less than red? no
|
||||
Is indigo less than green? no
|
||||
Is indigo less than blue? no
|
||||
Is indigo less than yellow? no
|
||||
Is indigo less than orange? no
|
||||
Is yellow less than red? no
|
||||
Is yellow less than green? yes
|
||||
Is yellow less than blue? yes
|
||||
Is yellow less than orange? no
|
||||
Is green less than blue? yes
|
||||
Is red less than orange? yes
|
||||
red orange yellow green blue indigo violet
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import java.util.*;
|
||||
|
||||
public class SortComp1 {
|
||||
public static void main(String[] args) {
|
||||
List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange");
|
||||
List<String> sortedItems = new ArrayList<>();
|
||||
Comparator<String> interactiveCompare = new Comparator<String>() {
|
||||
int count = 0;
|
||||
Scanner s = new Scanner(System.in);
|
||||
public int compare(String s1, String s2) {
|
||||
System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2);
|
||||
return s.nextInt();
|
||||
}
|
||||
};
|
||||
for (String item : items) {
|
||||
System.out.printf("Inserting '%s' into %s\n", item, sortedItems);
|
||||
int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);
|
||||
// when item does not equal an element in sortedItems,
|
||||
// it returns bitwise complement of insertion point
|
||||
if (spotToInsert < 0) spotToInsert = ~spotToInsert;
|
||||
sortedItems.add(spotToInsert, item);
|
||||
}
|
||||
System.out.println(sortedItems);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
import java.util.*;
|
||||
|
||||
public class OrderByPair {
|
||||
public static void main(String[] args) {
|
||||
List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange");
|
||||
Collections.sort(items, new Comparator<String>() {
|
||||
int count = 0;
|
||||
Scanner s = new Scanner(System.in);
|
||||
public int compare(String s1, String s2) {
|
||||
System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2);
|
||||
return s.nextInt();
|
||||
}
|
||||
});
|
||||
System.out.println(items);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
def inputOption($prompt; $options):
|
||||
def r:
|
||||
$prompt | stderr
|
||||
| input as $in
|
||||
| if $in|test($options) then $in else r end;
|
||||
r;
|
||||
|
||||
# Inserts item $x in the array input, which is kept sorted as per user input
|
||||
# assuming it is already sorted. $q is the prompt number.
|
||||
# Input: [$q; $a]
|
||||
# Output: [$qPrime, $aPrime]
|
||||
def insortRight($x):
|
||||
. as [$q, $a]
|
||||
| { lo: 0, hi: ($a|length), $q }
|
||||
| until( .lo >= .hi;
|
||||
( ((.lo + .hi)/2)|floor) as $mid
|
||||
| .q += 1
|
||||
| "\(.q): Is \($x) less than \($a[$mid])? y/n: " as $prompt
|
||||
| (inputOption($prompt; "[yn]") == "y") as $less
|
||||
| if ($less) then .hi = $mid
|
||||
else .lo = $mid + 1
|
||||
end)
|
||||
# insert at position .lo
|
||||
| [ .q, ($a[: .lo] + [x] + $a[.lo :]) ];
|
||||
|
||||
def order:
|
||||
reduce .[] as $item ( [0, []]; insortRight($item) )
|
||||
| .[1];
|
||||
|
||||
["violet red green indigo blue yellow orange"|splits(" ")]
|
||||
| order as $ordered
|
||||
| ("\nThe colors of the rainbow, in sorted order, are:",
|
||||
$ordered )
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
const nrequests = [0]
|
||||
const ordering = Dict("violet" => 7, "red" => 1, "green" => 4, "indigo" => 6, "blue" => 5,
|
||||
"yellow" => 3, "orange" => 2)
|
||||
|
||||
function tellmeifgt(x, y)
|
||||
nrequests[1] += 1
|
||||
while true
|
||||
print("Is $x greater than $y? (Y/N) => ")
|
||||
s = strip(readline())
|
||||
if length(s) > 0
|
||||
(s[1] == 'Y' || s[1] == 'y') && return true
|
||||
(s[1] == 'N' || s[1] == 'n') && return false
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function orderbypair!(a::Vector)
|
||||
incr = div(length(a), 2)
|
||||
while incr > 0
|
||||
for i in incr+1:length(a)
|
||||
j = i
|
||||
tmp = a[i]
|
||||
while j > incr && tellmeifgt(a[j - incr], tmp)
|
||||
a[j] = a[j-incr]
|
||||
j -= incr
|
||||
end
|
||||
a[j] = tmp
|
||||
end
|
||||
if incr == 2
|
||||
incr = 1
|
||||
else
|
||||
incr = floor(Int, incr * 5.0 / 11)
|
||||
end
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
const words = String.(split("violet red green indigo blue yellow orange", r"\s+"))
|
||||
println("Unsorted: $words")
|
||||
println("Sorted: $(orderbypair!(words)). Total requests: $(nrequests[1]).")
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
colors = { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }
|
||||
print("unsorted: " .. table.concat(colors," "))
|
||||
known, notyn, nc, nq = {}, {n="y",y="n"}, 0, 0
|
||||
table.sort(colors, function(a,b)
|
||||
nc = nc + 1
|
||||
if not known[a] then known[a]={[a]="n"} end
|
||||
if not known[b] then known[b]={[b]="n"} end
|
||||
if not (known[a][b] or known[b][a]) then
|
||||
io.write("Is '" .. a .. "' < '" .. b .."'? (y/n): ")
|
||||
nq, known[a][b] = nq+1, io.read()
|
||||
if a~=b then known[b][a] = notyn[known[a][b]] end
|
||||
end
|
||||
return known[a][b]=="y"
|
||||
end)
|
||||
print("sorted: " .. table.concat(colors," "))
|
||||
print("(" .. nq .. " questions needed to resolve " .. nc .. " comparisons)")
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
ClearAll[HumanOrderCheck]
|
||||
HumanOrderCheck[opt1_,opt2_]:=ChoiceDialog[Row@{"Is {",opt1,", ", opt2, "} ordered?"},{"Yes"->True,"No"->False}]
|
||||
Sort[{"violet","red","green","indigo","blue","yellow","orange"},HumanOrderCheck]
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import algorithm, strformat, strutils
|
||||
|
||||
let list = ["violet", "red", "green", "indigo", "blue", "yellow", "orange"]
|
||||
|
||||
var count = 0
|
||||
|
||||
proc comp(x, y: string): int =
|
||||
if x == y: return 0
|
||||
inc count
|
||||
while true:
|
||||
stdout.write &"{count:>2}) Is {x} less than {y} (y/n)? "
|
||||
let answer = stdin.readLine()[0]
|
||||
case answer
|
||||
of 'y': return -1
|
||||
of 'n': return 1
|
||||
else: echo "Incorrect answer."
|
||||
|
||||
var sortedList: seq[string]
|
||||
|
||||
for elem in list:
|
||||
sortedList.insert(elem, sortedList.upperBound(elem, comp))
|
||||
|
||||
echo "Sorted list: ", sortedList.join(", ")
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
let () =
|
||||
let count = ref 0 in
|
||||
let mycmp s1 s2 = (
|
||||
incr count;
|
||||
Printf.printf "(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: " (!count) s1 s2;
|
||||
read_int ()
|
||||
) in
|
||||
let items = ["violet"; "red"; "green"; "indigo"; "blue"; "yellow"; "orange"] in
|
||||
let sorted = List.sort mycmp items in
|
||||
List.iter (Printf.printf "%s ") sorted;
|
||||
print_newline ()
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
let () =
|
||||
let count = ref 0 in
|
||||
let mycmp s1 s2 = (
|
||||
incr count;
|
||||
Printf.printf "(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: " (!count) s1 s2;
|
||||
read_int ()
|
||||
) in
|
||||
let items = [|"violet"; "red"; "green"; "indigo"; "blue"; "yellow"; "orange"|] in
|
||||
Array.sort mycmp items;
|
||||
Array.iter (Printf.printf "%s ") items;
|
||||
print_newline ()
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
#!/usr/bin/perl
|
||||
|
||||
use strict; # https://rosettacode.org/wiki/Order_by_pair_comparisons
|
||||
use warnings;
|
||||
|
||||
sub ask
|
||||
{
|
||||
while( 1 )
|
||||
{
|
||||
print "Compare $a to $b [<,=,>]: ";
|
||||
<STDIN> =~ /[<=>]/ and return +{qw( < -1 = 0 > 1 )}->{$&};
|
||||
}
|
||||
}
|
||||
|
||||
my @sorted = sort ask qw( violet red green indigo blue yellow orange );
|
||||
print "sorted: @sorted\n";
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
(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>
|
||||
<span style="color: #000000;">qn</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d: Is %s < %s (Y/N)?:"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">qn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">})</span>
|
||||
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">())</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">return</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'Y'</span><span style="color: #0000FF;">?-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">:</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
|
||||
<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>
|
||||
<!--
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
def _insort_right(a, x, q):
|
||||
"""
|
||||
Insert item x in list a, and keep it sorted assuming a is sorted.
|
||||
If x is already in a, insert it to the right of the rightmost x.
|
||||
"""
|
||||
|
||||
lo, hi = 0, len(a)
|
||||
while lo < hi:
|
||||
mid = (lo+hi)//2
|
||||
q += 1
|
||||
less = input(f"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: ").strip().lower() == 'y'
|
||||
if less: hi = mid
|
||||
else: lo = mid+1
|
||||
a.insert(lo, x)
|
||||
return q
|
||||
|
||||
def order(items):
|
||||
ordered, q = [], 0
|
||||
for item in items:
|
||||
q = _insort_right(ordered, item, q)
|
||||
return ordered, q
|
||||
|
||||
if __name__ == '__main__':
|
||||
items = 'violet red green indigo blue yellow orange'.split()
|
||||
ans, questions = order(items)
|
||||
print('\n' + ' '.join(ans))
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
from functools import cmp_to_key
|
||||
|
||||
def user_cmp(a, b):
|
||||
return int(input(f"IS {a:>6} <, ==, or > {b:>6} answer -1, 0 or 1:"))
|
||||
|
||||
if __name__ == '__main__':
|
||||
items = 'violet red green indigo blue yellow orange'.split()
|
||||
ans = sorted(items, key=cmp_to_key(user_cmp))
|
||||
print('\n' + ' '.join(ans))
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
[ $ "Is " swap join
|
||||
$ " before " join
|
||||
swap join
|
||||
$ "? (y/n) " join
|
||||
input $ "y" = ] is askuser
|
||||
|
||||
$ "red orange yellow green blue indigo violet"
|
||||
say "Correct order --> "
|
||||
dup echo$ cr cr
|
||||
nest$ shuffle
|
||||
dup witheach [ echo$ sp ] cr cr
|
||||
sortwith askuser cr
|
||||
witheach [ echo$ sp ] cr
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
/*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; $=
|
||||
do j=1 for words(colors); q= inSort( word(colors, j), q)
|
||||
end /*j*/ /*poise questions the CBLF about order.*/
|
||||
say
|
||||
do i=1 for #; say ' query' right(i, length(#) )":" !.i
|
||||
end /*i*/ /* [↑] show the list of queries to CBLF*/
|
||||
say
|
||||
say 'final ordering: ' $
|
||||
exit 0
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
getAns: #= # + 1; _= copies('─', 8); y_n= ' Answer y/n'
|
||||
do try=0 until ansU='Y' | ansU='N'
|
||||
if try>0 then say _ '(***error***) incorrect answer.'
|
||||
ask= _ ' is ' center(x,6) " less than " center(word($, mid+1),6) '?'
|
||||
say ask y_n; parse pull ans 1 ansU; ansU= space(ans); upper ansU
|
||||
end /*until*/; !.#= ask ' ' ans; return
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
inSort: parse arg x, q; hi= words($); lo= 0
|
||||
do q=q-1 while lo<hi; mid= (lo+hi) % 2
|
||||
call getAns; if ansU=='Y' then hi= mid
|
||||
else lo= mid + 1
|
||||
end /*q*/
|
||||
$= subword($, 1, lo) x subword($, lo+1); return q
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
my $ask_count = 0;
|
||||
sub by_asking ( $a, $b ) {
|
||||
$ask_count++;
|
||||
constant $fmt = '%2d. Is %-6s [ less than | greater than | equal to ] %-6s? ( < = > ) ';
|
||||
constant %o = '<' => Order::Less,
|
||||
'=' => Order::Same,
|
||||
'>' => Order::More;
|
||||
|
||||
loop {
|
||||
my $input = prompt sprintf $fmt, $ask_count, $a, $b;
|
||||
return $_ with %o{ $input.trim };
|
||||
say "Invalid input '$input'";
|
||||
}
|
||||
}
|
||||
|
||||
my @colors = <violet red green indigo blue yellow orange>;
|
||||
my @sorted = @colors.sort: &by_asking;
|
||||
say (:@sorted);
|
||||
|
||||
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;
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
items = ["violet", "red", "green", "indigo", "blue", "yellow", "orange"]
|
||||
count = 0
|
||||
sortedItems = []
|
||||
items.each {|item|
|
||||
puts "Inserting '#{item}' into #{sortedItems}"
|
||||
spotToInsert = sortedItems.bsearch_index{|x|
|
||||
count += 1
|
||||
print "(#{count}) Is #{item} < #{x}? "
|
||||
gets.start_with?('y')
|
||||
} || sortedItems.length # if insertion point is at the end, bsearch_index returns nil
|
||||
sortedItems.insert(spotToInsert, item)
|
||||
}
|
||||
p sortedItems
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
items = ["violet", "red", "green", "indigo", "blue", "yellow", "orange"]
|
||||
count = 0
|
||||
p items.sort {|a, b|
|
||||
count += 1
|
||||
print "(#{count}) Is #{a} <, =, or > #{b}. Answer -1, 0, or 1: "
|
||||
gets.to_i
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import "/ioutil" for Input
|
||||
import "/fmt" for Fmt
|
||||
|
||||
// Inserts item x in list a, and keeps it sorted assuming a is already sorted.
|
||||
// If x is already in a, inserts it to the right of the rightmost x.
|
||||
var insortRight = Fn.new{ |a, x, q|
|
||||
var lo = 0
|
||||
var hi = a.count
|
||||
while (lo < hi) {
|
||||
var mid = ((lo + hi)/2).floor
|
||||
q = q + 1
|
||||
var prompt = Fmt.swrite("$2d: Is $6s less than $6s ? y/n: ", q, x, a[mid])
|
||||
var less = Input.option(prompt, "yn") == "y"
|
||||
if (less) {
|
||||
hi = mid
|
||||
} else {
|
||||
lo = mid + 1
|
||||
}
|
||||
}
|
||||
a.insert(lo, x)
|
||||
return q
|
||||
}
|
||||
|
||||
var order = Fn.new { |items|
|
||||
var ordered = []
|
||||
var q = 0
|
||||
for (item in items) {
|
||||
q = insortRight.call(ordered, item, q)
|
||||
}
|
||||
return ordered
|
||||
}
|
||||
|
||||
var items = "violet red green indigo blue yellow orange".split(" ")
|
||||
var ordered = order.call(items)
|
||||
System.print("\nThe colors of the rainbow, in sorted order, are:")
|
||||
System.print(ordered)
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
include xpllib; \for Print
|
||||
|
||||
int Items, Size, I, J, Gap, JG, T, C, Count;
|
||||
[Items:= ["violet", "red", "green", "indigo", "blue", "yellow", "orange"];
|
||||
Size:= 7;
|
||||
Count:= 0;
|
||||
Gap:= Size>>1;
|
||||
while Gap > 0 do
|
||||
[for I:= Gap to Size-1 do
|
||||
[J:= I - Gap;
|
||||
loop [JG:= J + Gap;
|
||||
Count:= Count+1;
|
||||
Print("%2d: Is %6s less than %6s (y/n)? ",
|
||||
Count, Items(J), Items(JG));
|
||||
repeat OpenI(1);
|
||||
C:= ChIn(1);
|
||||
until C=^y or C=^n;
|
||||
ChOut(0, C); CrLf(0);
|
||||
if C = ^y then quit;
|
||||
T:= Items(J); Items(J):= Items(JG); Items(JG):= T;
|
||||
J:= J - Gap;
|
||||
if J < 0 then quit;
|
||||
];
|
||||
];
|
||||
Gap:= Gap>>1;
|
||||
];
|
||||
Print("The colors of the rainbow, in sorted order, are:\n");
|
||||
for I:= 0 to Size-2 do Print("%s, ", Items(I));
|
||||
Print("%s\n", Items(I));
|
||||
]
|
||||
Loading…
Add table
Add a link
Reference in a new issue