How to resolve the algorithm Balanced brackets step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Balanced brackets step by step in the Swift programming language

Table of Contents

Problem Statement

Task:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Balanced brackets step by step in the Swift programming language

Source code in the swift programming language

import Foundation

func isBal(str: String) -> Bool {
  
  var count = 0
  
  return !str.characters.contains { ($0 == "["  ? ++count : --count) < 0 } && count == 0
  
}

isBal("[[[]]]") // true

isBal("[]][[]") // false

func randBrack(n: Int) -> String {
  
  var bracks: [Character] = Array(Repeat(count: n, repeatedValue: "["))
  
  for i in UInt32(n+1)...UInt32(n + n) {
    
    bracks.insert("]", atIndex: Int(arc4random_uniform(i)))
    
  }
  
  return String(bracks)
  
}

randBrack(2) // "]][["

func randIsBal(n: Int) {
  
  let (bal, un) = ("", "un")
  
  for str in (1...n).map(randBrack) {
    
    print("\(str) is \(isBal(str) ? bal : un)balanced\n")
    
  }
}

randIsBal(4)

//    ][ is unbalanced
//
//    ]][[ is unbalanced
//
//    []][[] is unbalanced
//
//    [][][[]] is balanced

  

You may also check:How to resolve the algorithm Egyptian division step by step in the F# programming language
You may also check:How to resolve the algorithm Random number generator (device) step by step in the REXX programming language
You may also check:How to resolve the algorithm Pangram checker step by step in the Prolog programming language
You may also check:How to resolve the algorithm Terminal control/Preserve screen step by step in the REXX programming language
You may also check:How to resolve the algorithm Currency step by step in the Delphi programming language