]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/balanced-brackets/balanced-brackets.factor
mason: temporary kludge until mason.db@factorcode.org is manually updated
[factor.git] / extra / rosetta-code / balanced-brackets / balanced-brackets.factor
1 ! Copyright (c) 2023 Alexander Ilin
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: combinators formatting kernel math random sequences
4 strings ;
5 IN: rosetta-code.balanced-brackets
6
7 ! https://rosettacode.org/wiki/Balanced_brackets
8
9 ! Task:
10
11 ! Generate a string with N opening brackets (“[”) and N closing
12 ! brackets (“]”), in some arbitrary order.
13
14 ! Determine whether the generated string is balanced; that is,
15 ! whether it consists entirely of pairs of opening/closing
16 ! brackets (in that order), none of which mis-nest.
17
18 ! Examples:
19
20 ! (empty)   OK
21 ! []        OK   ][        NOT OK
22 ! [][]      OK   ][][      NOT OK
23 ! [[][]]    OK   []][[]    NOT OK
24
25 : balanced? ( str -- ? )
26     0 swap [
27         {
28             { CHAR: [ [ 1 + t ] }
29             { CHAR: ] [ 1 - dup 0 >= ] }
30             [ drop t ]
31         } case
32     ] all? swap zero? and ;
33
34 : bracket-pairs ( n -- str )
35     [ "[]" ] replicate "" concat-as ;
36
37 : balanced-brackets-main ( -- )
38     5 bracket-pairs randomize dup balanced? "" "not " ?
39     "String \"%s\" is %sbalanced.\n" printf ;
40
41 MAIN: balanced-brackets-main