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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Balanced brackets step by step in the CLU 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 CLU programming language

Source code in the clu programming language

% This program needs the random number generator from
% "misc.lib" that comes with PCLU.

shuffle = proc [T: type] (a: array[t]) 
    aT = array[t]
    for i: int in int$from_to_by(aT$size(a)-1,0,-1) do
        x: int := aT$low(a) + i
        y: int := aT$low(a) + random$next(i+1)
        temp: T := a[x]
        a[x] := a[y]
        a[y] := temp
    end
end shuffle

brackets = proc (n: int) returns (string)
    br: array[char] := array[char]$[]
    for i: int in int$from_to(1,2*n) do
        if i<=n then array[char]$addh(br, '[')
        else array[char]$addh(br, ']')
        end
    end
    shuffle[char](br)
    return(string$ac2s(br))
end brackets

balanced = proc (br: string) returns (bool)
    depth: int := 0
    for c: char in string$chars(br) do
        if     c='[' then depth := depth + 1
        elseif c=']' then depth := depth - 1
        end
        if depth<0 then return(false) end
    end
    return(depth = 0)
end balanced

start_up = proc ()
    po: stream := stream$primary_output()
    d: date := now()
    random$seed(d.second + 60*(d.minute + 60*d.hour))
    
    for size: int in int$from_to(0, 10) do
        b: string := brackets(size)
        stream$puts(po, "\"" || b || "\": ")
        if balanced(b) then
            stream$putl(po, "balanced")
        else
            stream$putl(po, "not balanced")
        end
    end
end start_up

  

You may also check:How to resolve the algorithm Sorting algorithms/Quicksort step by step in the Prolog programming language
You may also check:How to resolve the algorithm Sorting algorithms/Bogosort step by step in the VBA programming language
You may also check:How to resolve the algorithm User input/Text step by step in the BBC BASIC programming language
You may also check:How to resolve the algorithm Round-robin tournament schedule step by step in the Julia programming language
You may also check:How to resolve the algorithm Hostname step by step in the BBC BASIC programming language