A Programming Job Interview Challenge #13 - Brackets, and Me...

Please spread the word if you like this content!
Digg Button submit to reddit
 

Ok, I've been doing the programming quizzes here and have a solution...

In Perl:


$FILE = "expressions.txt";
open(FILE) or die("Could not open expressions file.");
foreach $OLINE (<FILE>)
{
$LINE = $OLINE;
if ($LINE =~ m/(^[\]}\)>])|([\[{\(<]$)/)
{ print "bad : $OLINE" }
else
{
while ($LINE =~ m/(\[\])|({})|(\(\))|(<>)/)
{ $LINE =~ s/(\[\])|({})|(\(\))|(<>)//g }
$strLen = length($LINE);
if ($strLen > 1)
{ print "bad : $OLINE" }
else
{ print "good : $OLINE" }
}
}

And a C# console app to generate the "sample" strings (i.e. the "expressions.txt" file used above):




using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Creator();
//Console.ReadKey();
}
static void Creator()
{
Random r = new Random((DateTime.Now.DayOfYear + DateTime.Now.Millisecond) * (DateTime.Now.Second + DateTime.Now.Minute + 1));
string encs = "[{(<>)}]";

string sb = "";
for (int i = 0; i < 100; i++)
{
sb = "";
bool good = (r.Next(0, 100) > 50) ? true : false;
int strlen = r.Next(1, 21) * 2;
for (int j = 0; j < strlen; j++)
{
if (!good)
sb = String.Format("{0}{1}", sb, encs[r.Next(0, encs.Length)]);
else
{
int p = r.Next(0, encs.Length / 2);
int q = r.Next(0, 3);
if (q == 0)
sb = String.Format("{0}{1}{2}", encs[p], sb, encs[encs.Length - p - 1]);
else if (q == 1)
sb = String.Format("{0}{1}{2}", sb, encs[p], encs[encs.Length - p - 1]);
else
sb = String.Format("{0}{1}{2}", encs[p], encs[encs.Length - p - 1], sb);
}
}
//Console.WriteLine(String.Format("{0}: {1}", good, sb.ToString()));
Console.WriteLine(sb);
}
}
}
}

I couldn't spend that much time on this, as I am at work. Ergo, I'm a little disappointed with the Perl, although it was my first Perl program ever!


I'm particularly curious about how I could have done some sort of recursive check. Please give any suggestions to the Perl script that would make it as close to a one-liner regex check.


~simon

posted @ Tuesday, July 22, 2008 8:46 AM

Print

Comments on this entry:

No comments posted yet.

Your comment:



 (will not be displayed)


 
 
 
Please add 2 and 2 and type the answer here:
 

Live Comment Preview:

 
«July»
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789