Last active
October 28, 2023 00:06
-
-
Save KelOkekpe/cb701c7bfea689e89a08ccaef57d7e73 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#this is the condensed version without explanations | |
def validate_brackets(s, valid = false) | |
opening_brackets = ["{", "[", "(" ] | |
closing_brackets = {"}"=> "{", "]"=> "[", ")"=> "("} | |
brackets_arr = s.gsub(" ", "").split("") | |
last_opened_type = [] | |
iterations = 0 | |
brackets_arr.each do |b| | |
opening_brackets.include?(b) ? opened = true : closed = true | |
if opened | |
last_opened_type.push(b) | |
elsif closed | |
closing_brackets[b] == last_opened_type.last ? last_opened_type.pop() : break | |
end | |
iterations +=1 | |
end | |
valid = true if iterations == brackets_arr.size | |
puts valid | |
end | |
# this is the long, more readable version with explanations | |
def validate_brackets(s) | |
valid = false # by default this method returns false | |
opening_brackets = ["{", "[", "(" ] # make an array of valid opening brackets | |
closing_brackets = {"}"=> "{", "]"=> "[", ")"=> "("} # hash of valid closing bracket types and their corresponding open bracket pairs | |
brackets_arr = s.gsub(" ", "").split("") | |
last_opened_type = [] # store value of the last bracket that was opened but not closed | |
iterations = 0 | |
brackets_arr.each do |b| | |
# evaluate if the element is an opening or closing bracket | |
opened = true if opening_brackets.include?(b) | |
closed = true if closing_brackets.keys.include?(b) | |
if opened | |
last_opened_type.push(b) # if it is an opening bracket, push the value to the array of the last opened type array | |
elsif closed | |
if closing_brackets[b] == last_opened_type.last # if its a closing bracket, validate that the element in the last opened array corresponds with the closing type ( ie. "}" should map to "{"" ) | |
last_opened_type.pop() # remove the last opened bracket type from the array, this essentially means it has been closed | |
elsif closing_brackets[b] != last_opened_type.last # if the closing bracket does not correspond with the last opened bracket, this represents a faulty inpuy | |
break | |
end | |
end | |
iterations +=1 # keep count of iterations to determine if entire string was evaluated without error | |
end | |
valid = true if iterations == brackets_arr.size # make return value true if no rule breaking conditions were met | |
puts valid | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment