in reply to Shuffling cards

Hey, I'm trying to Perl some BIO past papers (a British programming contest) but I have some results that I can't explain. The program has to take in a string where b, i and o are functions and have coefficients and groupings such as b3(io) does b then io 3 times. Full explanation is here (question two):

BIO Past Papers

Ok, I finally checked the full explanation. Here's my sample code to solve the assignment:
#!/usr/bin/perl -l use strict; use warnings; my @pack=1..8; my %disp; @disp{qw/b i o/}=map { my $t=$_; sub { @_[@$t] }; } [1..7,0], [4,0,5,1,6,2,7,3], [0,4,1,5,2,6,3,7]; sub parse { for (@_) { my $c; s/[()]/ $& eq '(' ? '(=' . $c++ . '=' : '=' . --$c . '=)' /ge; s/(\d)([bio])/$2 x $1/ge; 1 while s/(\d) \(=(\d+)= (.+?) =\2=\)/$3 x $1/gex; } } while (<>) { parse $_; @pack=$disp{$_}->(@pack) for /./g; print "@pack"; } __END__
Please note that:
  1. I don't do any input validation, for the rules partly explicitly partly implicitly state that I must trust it,
  2. this is certainly not the most efficient way to do this, but it is IMHO adequate to the nature of the problem, as of the description,
  3. Also, the sub parse() is by no means necessary, but I wanted to keep it separate it from the main loop.

      HTH.

Replies are listed 'Best First'.
Re^2: Shuffling cards
by Anonymous Monk on Feb 23, 2005 at 14:11 UTC
    Yours would fail if you have 10 or more nested parens.
      Yours would fail if you have 10 or more nested parens.
      It won't any more, I made the minimal correction that solved this and I hope you will apologize me for not having pointed out explicitly having done so (but it's really a one-char correction).

      Incidentally, to be fair I'm not really sure if with input strings limited to 20 chars (as of the rules!!) you can have more than 10 nested parens and thinking about it one more second... no, you can't!

        And then you didn't fix the other \d. Now it still fails on "10b". Yes, I know the rules are for people who can't program and uses arbitrary limits to allow even the most sloppy coders to score a few marks. But that's no excuse for code on perlmonks, is it? ;-)