Dutch national flag problem: Difference between revisions

m (syntax highlighting fixup automation)
Line 2,111:
Dutch Sorted balls: Red,Red,Red,Red,Red,Red,Red,Red,Red,White,White,White,White,White,White,White,Blue,Blue,Blue,Blue,Blue,Blue
Is sorted: true
</pre>
 
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
 
'''Adapted from [[#Wren|Wren]]'''
 
In the following, /dev/random is used as a source of entropy.
In a bash or bash-like environment, a suitable invocation would
be as follows:
<pre>
< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mcnr -f dnf.jq
</pre>
'''dnf.jq'''
<syntaxhighlight lang=jq>
# Output: a PRN in range(0; .)
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
 
def colors: ["Red", "White", "Blue"];
 
def colorMap: {"Red": 0, "White": 1, "Blue": 2 };
 
def task($nballs):
def sorted:
. == sort_by(colorMap[.]);
def generate:
[range(0; $nballs) | colors[ 3|prn ] ]
| if sorted then generate else . end;
generate
| "Before sorting : \(.)",
"After sorting : \(sort_by(colorMap[.]))" ;
 
task(9)
</syntaxhighlight>
{{output}}
<pre>
Before sorting : ["Blue","Red","Blue","White","Blue","White","Red","White","Blue"]
After sorting : ["Red","Red","White","White","White","Blue","Blue","Blue","Blue"]
</pre>
 
2,462

edits