Jump to content

Balanced brackets: Difference between revisions

→‎Factor: Add a full task implementation: generate random string and check if it's balanced. The solution doesn't use local variables.
(→‎{{header|Factor}}: Remove an incorrect solution: it fails to check the negative balance, and doesn't implement the random string generation.)
(→‎Factor: Add a full task implementation: generate random string and check if it's balanced. The solution doesn't use local variables.)
Line 3,244:
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: combinators formatting kernel math random sequences strings ;
This code implements the second part of the task: it reads from standard input an arbitrary string of opening and closing brackets, and checks whether it's balanced or not.
IN: rosetta-code.balanced-brackets
 
: balanced? ( str -- ? )
0 swap [
{
{ CHAR: [ [ 1 + t ] }
{ CHAR: ] [ 1 - dup 0 >= ] }
[ drop t ]
} case
] all? swap zero? and ;
 
: bracket-pairs ( n -- str )
[ "[]" ] replicate "" concat-as ;
 
: balanced-brackets-main ( -- )
5 bracket-pairs randomize dup balanced? "" "not " ?
"String \"%s\" is %sbalanced.\n" printf ;
 
MAIN: balanced-brackets-main</syntaxhighlight>
 
ThisThe code below implements only the second part of the task: it reads from standard input an arbitrary string of opening and closing brackets, and checks whether it's balanced or not. Unlike the solution above, this one uses local variables.
<syntaxhighlight lang="factor">USING: io formatting locals kernel math sequences unicode.case ;
IN: balanced-brackets
8

edits

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