Order by pair comparisons: Difference between revisions
Content added Content deleted
Alpha bravo (talk | contribs) (Added AutoHotkey) |
|||
Line 679: | Line 679: | ||
[red, yellow, green, orange, blue, indigo, violet] |
[red, yellow, green, orange, blue, indigo, violet] |
||
</pre> |
</pre> |
||
=={{header|jq}}== |
|||
{{trans|Wren}} |
|||
{{works with|jq}} |
|||
'''Works with gojq, the Go implementation of jq''' |
|||
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. |
|||
<lang jq>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 )</lang> |
|||
'''Recommended Invocation Options''': -nRrc |
|||
'''Sample Transcript''' |
|||
<pre> |
|||
"1: Is red less than violet? y/n: "y |
|||
y |
|||
"2: Is green less than violet? y/n: "y |
|||
y |
|||
"3: Is green less than red? y/n: "n |
|||
n |
|||
"4: Is indigo less than green? y/n: "n |
|||
n |
|||
"5: Is indigo less than violet? y/n: "y |
|||
y |
|||
"6: Is blue less than indigo? y/n: "y |
|||
y |
|||
"7: Is blue less than green? y/n: "n |
|||
n |
|||
"8: Is yellow less than blue? y/n: "y |
|||
y |
|||
"9: Is yellow less than green? y/n: "y |
|||
y |
|||
"10: Is yellow less than red? y/n: "n |
|||
n |
|||
"11: Is orange less than blue? y/n: "y |
|||
y |
|||
"12: Is orange less than yellow? y/n: "y |
|||
y |
|||
"13: Is orange less than red? y/n: "n |
|||
n |
|||
The colors of the rainbow, in sorted order, are: |
|||
["red","orange","yellow","green","blue","indigo","violet"] |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |