Balanced brackets: Difference between revisions
Content added Content deleted
imported>Brie (Add Nu implementation) |
|||
Line 5,612: | Line 5,612: | ||
'][[][]]]][[[[][]' is not balanced |
'][[][]]]][[[[][]' is not balanced |
||
'][][][][][[][[]]][' is not balanced</pre> |
'][][][][][[][[]]][' is not balanced</pre> |
||
=={{header|Nu}}== |
|||
<syntaxhighlight lang="nu"> |
|||
def gen_brackets [n: int] { 1..$in | each {["[" "]"]} | flatten | shuffle | str join } |
|||
def check_brackets [] { |
|||
split chars | reduce --fold 0 {|x, d| |
|||
if ($d < 0) {-1} else { |
|||
$d + (if ($x == "[") {1} else {-1}) |
|||
} |
|||
} | $in > -1 |
|||
} |
|||
1..10 | each {gen_brackets $in | {brackets: $in, valid: ($in | check_brackets)}} | print |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
╭───┬──────────────────────┬───────╮ |
|||
│ # │ brackets │ valid │ |
|||
├───┼──────────────────────┼───────┤ |
|||
│ 0 │ ][ │ false │ |
|||
│ 1 │ []][ │ false │ |
|||
│ 2 │ [[][]] │ true │ |
|||
│ 3 │ [[[][]]] │ true │ |
|||
│ 4 │ ]]][[[[][] │ false │ |
|||
│ 5 │ [][][][[[]]] │ true │ |
|||
│ 6 │ ]]]]][]][[[[[[ │ false │ |
|||
│ 7 │ ][[][]]]][[][[[] │ false │ |
|||
│ 8 │ []]]][][][[][]][[[ │ false │ |
|||
│ 9 │ ][][][[[[[]]]][[]][] │ false │ |
|||
╰───┴──────────────────────┴───────╯ |
|||
</pre> |
|||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |