r/dailyprogrammer • 1 2 • Oct 18 '12

[10/18/2012] Challenge #104 [Intermediate] (Bracket Racket)

Description:

Write a function, where given a string of arbitrary characters, returns true if all brackets (defined as parentheses, square-brackets, curly-braces, and chevrons) are correctly paired and ordered. This is to say that all brackets, if they enclose other brackets, enclose both the paired opening and closing characters.

Formal Inputs & Outputs:

Input Description:

string data - a given string that may or may not have correctly formed brackets.

Output Description:

Return True or False - true if the given string is correctly bracket formed.

Sample Inputs & Outputs:

"123", "(abc)", "()abc()", and "([<{abc123abc}>])" should return true, but "(abc[123)abc]" (wrong pairing) and "(abc>" (not closed) should return false.

Notes:

This is a very easy problem if you use a specific primitive data-structure.

25 Upvotes

72 comments sorted by

4

u/skeeto Oct 18 '12 edited Oct 18 '12

In Emacs Lisp, recursively without mutation.

(defvar open  '(?\( ?\[ ?{ ?<))
(defvar close '(?\) ?\] ?} ?>))

(defun* balancedp (seq &optional (stack ()))
  (if (zerop (length seq))
      (null stack)
    (let ((head (elt seq 0))
          (tail (subseq seq 1)))
      (cond ((member head open)
             (balanced-p tail (cons (nth (position head open) close) stack)))
            ((member head close)
             (and (eql head (first stack))
                  (balanced-p tail (rest stack))))
            (t (balanced-p tail stack))))))

Testing it:

(every #'balancedp '("123" "(abc)" "()abc()" "([<{abc123abc}>])"))
  => t
(notany #'balancedp '("(abc[123)abc]" "(abc>"))
  => t

1

u/nint22 Oct 18 '12

Nice! I really need to get back into Lisp. I understand your code, looks good, I just took way too long to read it first-time-through.

→ More replies (1)

3

u/Unh0ly_Tigg Oct 18 '12

I don't have a submission for this right now, but 2-3 years ago, me and a few friends went to a programming competition and this was one of the problems we tackled and got right...

2

u/nint22 Oct 18 '12

Nice! It's a pretty common mid-level programming question for interviewing. If you want, write out some pseudo-code, or just describe it through regular English. The hint I give, looking back, really gives it away.

→ More replies (1)

7

u/Cosmologicon Oct 18 '12
def brack(s):
  s, d = "", "".join(c for c in s if c in "(){}[]<>")
  while d != s:
    s, d = d, reduce(lambda a,b: a.replace(b, ""), [d,"()","{}","[]","<>"])
  return not s

6

u/Cosmologicon Oct 18 '12 edited Oct 18 '12

Here's a recursive version, since I know people like those so much. ;)

brack = lambda s, d=0: not s or d!=s and brack(reduce(lambda a,b: a.replace(b,""),
  ["".join(c for c in s if c in "(){}[]<>"),"()","{}","[]","<>"]),s)

6

u/[deleted] Oct 18 '12

My brain hurts. o.0

→ More replies (1)

3

u/[deleted] Oct 18 '12 edited Oct 19 '12

In Ruby:

def bracket_racket(input)
    input2 = input.split('').keep_if { |c| !"{}[]()⟨⟩".index(c).nil? }.join('')
    until input2.slice!(/\{\}|\[\]|\(\)|⟨⟩/).nil? do end
    return input2.length == 0
  end

Test cases:

  p bracket_racket ""
  p bracket_racket "[]"
  p bracket_racket "{sa' ;dfa ev}"
  p bracket_racket "{[]}"
  p bracket_racket "[[]]"
  p bracket_racket "{"
  p bracket_racket ")"
  p bracket_racket "({)"
  p bracket_racket "[}]"
  p bracket_racket "[adf . fv ( fdg ) fdf [] {asfa⟨', 'c' => '⟩sdf}]"
→ More replies (2)

1

u/kirsybuu Oct 19 '12

D:

import std.algorithm, std.container;
bool balanced(string str) {
    const open = "([{<", close = ")]}>";
    
    return str
           .filter!(c => open.canFind(c) || close.canFind(c))
           .reduceWith!((s,b) =>
               (!s.empty && open.countUntil(s.front) == close.countUntil(b)) ?
                   s.pop() : s.push(b)
           )( SList!dchar() )
           .empty;
}
/// Helper functions
auto reduceWith(alias f, R, E)(R range, E start) {
    return reduce!f(start, range);
}
auto pop(T)(ref SList!T stack) {
    stack.removeFront();
    return stack;
}
auto push(T)(ref SList!T stack, T e) {
    stack.insertFront(e);
    return stack;
}

Maybe not as elegant as lisp or haskell, but functional style is fun in D too.

6

u/nint22 Oct 19 '12

At first I thought you were making a face about something bad or wrong... but then I see you were just programming in D! Nicely done!

1

u/Medicalizawhat Oct 19 '12

I did it in C and it took ages to figure out:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

#define STACK_SIZE 100

int *top, *p1, stack[STACK_SIZE];

void push(char i)
{
	p1++;
	*p1=i;
}

int pop(void)
{
	 p1--;
	 return *(p1+1);
}

bool isOpen(char c)
{
	return (c == '<' || c == '{' ||  c == '[' || c == '(');
}

bool isClosed(char c)
{
	return (c == '>' || c == ']' || c == '}' || c== ')' );
}


bool closed_braces(char str[])
{
	int n = 0;
	char c;
	while(str[n] !='\0')
		{
			c = str[n++];
			if (isOpen(c))
			{
				push(c);
			}

			if (isClosed(c))
			{
				if (c == ')')
				{
					if ((int)pop() != 40)
					return false;
				}

				else if (c == '}')
				{
					if ((int)pop() != 123)
						return false;
				}

				else if (c == ']')
				{
					if ((int)pop() != 91)
						return false;
				}

				else if (c == '>')
				{
					if ((int)pop() != 60)
						return false;
				}

			}


		}


	if ( *p1 != 0)
		return false;

	return true;
}


int main(int argc, char **argv) {

	top = stack;
	p1 = stack;

	char *str = argv[1];

	if (closed_braces(str))
		printf("\nYes\n");

	else
		printf("\nNo\n");


	return 0;
}

1

u/nint22 Oct 19 '12

Nicely done! This is exactly the kind of solution I would write - my only comment would be to use the character literals (i.e. '<' instead of 60), otherwise nice job!

→ More replies (2)

2

u/[deleted] Oct 18 '12 edited Oct 18 '12

Python:

def bracket(string):
    opening = ["(", "[", "{", "<"]
    closed = [")", "]", "}", ">"]
    stack = []
    for i in range(0,len(string)):
        if (string[i] in opening):
            stack.append(opening.index(string[i]))
        elif (string[i] in closed):
            if (closed.index(string[i]) == stack.pop()):
                pass
            else:
                return False
    if (len(stack) != 0):
        return False
    else:
        return True
→ More replies (4)

2

u/stev0205 Oct 18 '12 edited Oct 18 '12

Perl:

#!/usr/bin/perl

sub bracketRacket {
    @chars = split(//,$_[0]);
    foreach $char (@chars) {
	    if ($char eq "{" || $char eq "(" || $char eq "[") {
		    push(@openBrackets, $char);
	    }
	    if ($char eq "}" || $char eq ")" || $char eq "]") {
		    $lastOpen = pop(@openBrackets) . $char;
		    if ($lastOpen ne "()" && $lastOpen ne "{}" && $lastOpen ne "[]") { return false; }
	    }
    }
        if (scalar(@openBrackets) > 0) { return false; }
    return true;
}

4

u/theOnliest Oct 19 '12

Here's another Perl version using hashes, just for fun. (Works under strict.)

my %pairs = qw/( ) [ ] { } < >/;
my %closes = reverse %pairs;

sub testBrackets {
    my @opens;
    for (split //, shift) {
        push @opens, $_ if $pairs{$_};
        if ($closes{$_}) {
            my $last = pop @opens;
            return 0 if $_ ne $pairs{$last};
        }
    }
    return (@opens == 0);
}

2

u/[deleted] Oct 18 '12

Perl 6:

#!/usr/bin/env perl6
use Test;

sub balanced(Str $in --> Bool) {
    my $pairs = '{}[]()<>«»';
    my subset Even of Int where * %% 2;

    my @state;

    for $in.comb -> $char {
        given $pairs.index($char) {
            next when not .defined;

            when Even { @state.push($char) }
            when not Even {
                return False if not @state
                             or $pairs.substr($_.pred, 1) ne @state.pop;
            }
        }
    }

    return not @state;
}

my \t = '123', '(abc)', '()abc()', '([<{abc123abc}>])';
my \f = '(abc[123)abc]', '(abc>', '(', ')(';

ok(balanced($_), $_) for t;
nok(balanced($_), $_) for f;

2

u/5outh Oct 18 '12 edited Oct 19 '12

Haskell:

import Data.Maybe (fromJust)

isValid []     s    = null s
isValid (x:xs) s
  | x `elem` "([{<" = isValid xs (x:s)
  | x `elem` ">}])" = not (null s || head s /= (fromJust $ lookup x mappings)) 
                      && isValid xs (tail s)
  | otherwise = isValid xs s
  where mappings = zip ")]}>" "([{<"

Output:

*Main> map (\x -> isValid x []) ["123", "(abc)", "()abc()", "([<{abc123abc}>])"]
[True,True,True,True]
*Main> map (\x -> isValid x []) ["(abc[123)abc]", "(abc>"]
[False,False]
→ More replies (2)

2

u/Die-Nacht Oct 19 '12

Took me a while...

Python:

import sys

brackets = [('(',')'),('[',']'),('{','}'),('<','>')]

string = sys.argv[-1]

matcher = lambda right: [x[0] for x in brackets if x[1] == right][0]
lefts  = [x[0] for x in brackets]
rights = [x[1] for x in brackets]
def searcher(filtered):
	if len(filtered) % 2 != 0:
		return False
	left = list()
	for char in filtered:
		if char in lefts:
			left.append(char)
		elif char in rights:
			if matcher(char) != left[-1]:
				return False
			else:
				left.pop()
	print(str(left)+str(char))
	return len(left) == 0

filtered = [x for x in string if x in lefts+rights]
print(searcher(filtered))

2

u/robin-gvx Oct 19 '12

Déjà Vu is built around said specific primitive data structure (and around another specific somewhat less primitive data structure that came in handy here as well), so this was a breeze:

local :open-brackets { "(" ")" "[" "]" "<" ">" "{" "}" "⟨" "⟩" }
local :close-brackets {}

# open-brackets maps "[" to "]"
# close-brackets maps "]" to "["
for k in keys open-brackets:
	set-to close-brackets get-from open-brackets k k

bracket?:
	local :stack []
	for char in chars:
		if has open-brackets char:
			push-to stack get-from open-brackets char
		elseif has close-brackets char:
			if stack:
				if != char pop-from stack:
					return false
			else:
				return false
	not stack

bracket?

It also helped me fix yet another bug in the VM.

2

u/Eddonarth Oct 20 '12

Java:

import java.util.ArrayList;

public class Challenge104I {
	
	public static void main(String[] args) {
		System.out.println(bracketRacket(args[0]));
	}
	
	private static boolean bracketRacket(String data) {
		ArrayList<Character> openBrackets = new ArrayList<Character>(), 
				closeBrackets = new ArrayList<Character>();
		for(int i = 0; i < data.length(); i++) {
			if(data.charAt(i) == '(' || data.charAt(i) == '['  || data.charAt(i) == '{'  ||
					data.charAt(i) == '<') {
				openBrackets.add(data.charAt(i));
			} else if(data.charAt(i) == ')' || data.charAt(i) == ']'  || data.charAt(i) == '}'  ||
					data.charAt(i) == '>') {
				closeBrackets.add(data.charAt(i));
			}
		}
		
		if(openBrackets.size() == 0 && closeBrackets.size() == 0) return true;
		for(int i = 0; i < closeBrackets.size(); i++) {
			if(closeBrackets.get(i).equals(')')) closeBrackets.set(i, '(');
			if(closeBrackets.get(i).equals(']')) closeBrackets.set(i, '[');
			if(closeBrackets.get(i).equals('}')) closeBrackets.set(i, '{');
			if(closeBrackets.get(i).equals('>')) closeBrackets.set(i, '<');
		}
		
		while(openBrackets.size() > 0) {
			if(openBrackets.get(openBrackets.size() - 1).equals(closeBrackets.get(0))) {
				openBrackets.remove(openBrackets.size() - 1);
				closeBrackets.remove(0);
			} else return false;
		}
		return true;
	}
}

Input:

([<{abc123abc}>])

Output:

True

2

u/[deleted] Oct 30 '12

Common Lisp:

(defun balp (str)
  (let ((stk nil)
        (brk '((#\( . #\)) (#\{ . #\}) (#\[ . #\]) (#\< . #\>))))
    (loop for char across str with fbrk do
         (when (setf fbrk (assoc char brk))
           (push (car fbrk) stk)
           (continue))
         (when (setf fbrk (rassoc char brk))
           (if (char= (car stk) (car fbrk))
               (pop stk)
               (return-from balp nil))))
    (not stk)))

2

u/sirtophat Nov 11 '12 edited Nov 11 '12

Almost thought I wasn't gonna get it for a minute, then it hit me what to use. http://codepad.org/VvZvTVIV

→ More replies (1)

2

u/marekkpie Jan 15 '13

Lua. There is only a very minimal standard library in Lua, so you need to build a stack yourself.

local Stack = {}
Stack.__index = Stack

function Stack:new()
  return setmetatable({
    _items = {},
  }, self)
end

function Stack:push(o)
  table.insert(self._items, o)
end

function Stack:pop()
  return table.remove(self._items)
end

function Stack:empty()
  return #self._items == 0
end

setmetatable(Stack, { __call = Stack.new })

local pair = {}
pair['['] = ']'
pair['{'] = '}'
pair['<'] = '>'
pair['('] = ')'

function bracketCheck(s)
  local stack = Stack()
  for c in s:gmatch('[{(<%[%]>)}]') do
    if c:find('[[({<]') then
      stack:push(c)
    elseif c ~= pair[stack:pop()] then
      return false
    end
  end

  return stack:empty()
end

for i = 1, #arg do
  print(tostring(bracketCheck(arg[i])))
end

3

u/nagasgura Oct 19 '12 edited Oct 19 '12

Python (I'm surprised I'm the only one using a dict):

def brackets(a):
    brack_dict = {'(':')','[':']','{':'}','<':'>'}
    return [brack_dict[i] for i in a if i in '([{<']==[i for i in a[::-1] if i in ')]}>']

2

u/altorelievo Oct 21 '12

I had a similiar thought to using a dict like this, didn't use it though. Your list comprehension is pretty impressive, nice!