Balanced brackets: Difference between revisions

→‎{{header|jq}}: second (high-entropy) solution
(→‎{{header|jq}}: second (high-entropy) solution)
Line 4,476:
{{works with|jq}}
'''Works with gojq, the Go implementation of jq.'''
 
<syntaxhighlight lang=jq>
In this entry, two solutions are given: the first uses
an external source of entropy and jq's `until` control structure;
the second uses a low-entropy PRNG based on jq's `now`,
and `gsub/2.`
===High entropy solution using `until`===
<syntaxhighlight lang=bash>
< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mcnr '
 
# Output: a PRN in range(0;$n) where $n is .
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 prb: 2 | prn == 0;
 
def balanced:
{array: explode, parity: 0}
| until( .result | type == "boolean";
if .array == [] then .result = (.parity == 0)
else .parity += (.array[0] | if . == 91 then 1 else -1 end)
| if .parity < 0 then .result = false
else .array |= .[1:]
end
end ).result ;
 
def task($n):
if $n%2 == 1 then null
else [ (range(0; $n) | if prb then "[" else "]" end) // ""]
| add
| "\(.): \(balanced)"
end;
 
task(0),
task(2),
(range(0;10) | task(4))
</syntaxhighlight>
{{output}}
<pre>
: true
[[[[: false
[[][[: false
][][[: false
]][][: false
[][]]: true
]]][[: false
][[][: false
[]][[[: false
[]]][[: false
]]]][[[: false
[]][: false
</pre>
===Low entropy solution with `gsub`===
<syntaxhighlight lang=jq>
def prb: (now|tostring[-1:] | tonumber) % 2 == 0;
 
def balanced:
if length==0 then true
Line 4,487 ⟶ 4,546:
else
(reduce range(0; $n) as $i ("";
. + (if psrbprb then "[" else "]" end) ))
| "\(.): \(balanced)"
end;
Line 4,496 ⟶ 4,555:
</syntaxhighlight>
{{output}}
Similar to above.
<pre>
 
: true
[]: true
]][]: false
[[[[: false
[[[[: false
[][]: true
][][: false
[]]]: false
]]]]: false
]]][: false
[]][: false
][[]: false
</pre>
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Printf
2,471

edits