Task:

 Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. 
 Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.


Examples

   (empty)      OK
   []           OK   
   [][]         OK   
   [[][]]       OK 
   ][         NOT OK
   ][][       NOT OK
   []][[]     NOT OK



 
section .data
 
MsgBalanced: db "OK", 10
MsgBalancedLen: equ 3
 
MsgUnbalanced: db "NOT OK", 10
MsgUnbalancedLen: equ 7
 
MsgBadInput: db "BAD INPUT", 10
MsgBadInputLen: equ 10
 
Open: equ '['
Closed: equ ']'
 
section .text
 
BalancedBrackets:
 
  xor rcx, rcx
  mov rsi, rdi
  cld
 
  processBracket:
    lodsb
    cmp al, 0
    je determineBalance
 
    cmp al, Open
    je processOpenBracket
 
    cmp al, Closed
    je processClosedBracket
 
    mov rsi, MsgBadInput
    mov rdx, MsgBadInputLen
    jmp displayResult
 
    processOpenBracket:
      add rcx, 1
      jmp processBracket
 
    processClosedBracket:
      cmp rcx, 0
      je unbalanced
 
      sub rcx, 1
      jmp processBracket
 
 
  determineBalance:
    cmp rcx, 0
    jne unbalanced
 
    mov rsi, MsgBalanced
    mov rdx, MsgBalancedLen
    jmp displayResult
 
  unbalanced:
    mov rsi, MsgUnbalanced
    mov rdx, MsgUnbalancedLen
 
  displayResult:
    mov rax, 1
    mov rdi, 1
    syscall
    ret
 