]> gitweb.factorcode.org Git - factor.git/commitdiff
rosetta-code.balanced-brackets: add full task implementation
authorAlexander Ilin <alex.ilin@protonmail.com>
Tue, 8 Aug 2023 03:00:21 +0000 (05:00 +0200)
committerAlexander Ilin <alex.ilin@protonmail.com>
Tue, 8 Aug 2023 03:00:54 +0000 (05:00 +0200)
Add the random string generation according to the task description, and the
sample result output. Reimplement the solution without using locals.

extra/rosetta-code/balanced-brackets/balanced-brackets.factor

index a2c4ef206a52aab91ea5454c999cd0da7faa8002..902ba05777902684e9a67f5a7501d7ef07748a18 100644 (file)
@@ -1,6 +1,7 @@
-! Copyright (c) 2012 Anonymous
+! Copyright (c) 2023 Alexander Ilin
 ! See https://factorcode.org/license.txt for BSD license.
-USING: combinators kernel math sequences ;
+USING: combinators formatting kernel math random sequences
+strings ;
 IN: rosetta-code.balanced-brackets
 
 ! https://rosettacode.org/wiki/Balanced_brackets
@@ -21,15 +22,20 @@ IN: rosetta-code.balanced-brackets
 ! [][]      OK   ][][      NOT OK
 ! [[][]]    OK   []][[]    NOT OK
 
-:: balanced? ( str -- ? )
-    0 :> counter!
-    t :> ok!
-    str [
+: balanced? ( str -- ? )
+    0 swap [
         {
-            { CHAR: [ [ 1 ] }
-            { CHAR: ] [ -1 ] }
-            [ drop 0 ]
-        } case counter + counter!
-        counter 0 < [ f ok! ] when
-    ] each
-    ok [ counter 0 <= ] [ f ] if ;
+            { 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