Hello
punitpawar
this seems like an assignement to learn Perl by resolving problems.. anyway the challenge was accepted and you got good replies.
Be sure to understand the clean and sharp
BrowserUk's answer that seems to me the right Perl standard way to get job done. Note in the
BrowserUk's answer the tecnique is called 'recursive' not 'iterative'. Be sure to understand the two concept.
In Perl there are always more ways to get the job done: the tricky
betterworld's attempt (that was my first thought too..) uses the stringification got from
Data::Dumper to do the math.
The wise monk
choroba uses instead a powerfull tool to do the math: many modules on CPAN are powerfull and reliable tools. Take your time to learn a bounch of them to have always at your pocket: Look at
Data::Walk to learn what it can do and compare with the
choroba's solution.
Other modules can be used for this task:
Marpa::R2 recent examples by
GrandFather and again
choroba let me think is possible with this module too.
Occasionally there is also the way you never have to choose for production code, but that can be useful while learning: the 'evil eval string' is one of my favourites...
Notice that in the below code I use not the ArrayofArray but the strings as stated in your OP ('given nested list of integers')
#!/usr/bin/perl
use warnings;
use strict;
my @str = ('{{1,1},2,{1,1}}', # the function sho
+uld return 10
'{1,{4,{6}}}', # the function sho
+uld return 27
'{{1,1,1,1},{1,1,{2,2}},{1,{2,{3,3}}}}', # Buk 56
'{1,{{13}}}' # mine.. two digit
+ tests 40
);
my $w = 0; # weight or depth
print "$_\t=>\t".(
eval join ('',
map{ /{/ ? ++$w && '(' :
/\d/ ? $w.'*'.$_ :
/,/ ? '+' :
/}/ ? $w-- && ')' :
$_
}($_=~/\d+|./g)
)
)."\n" for @str;
#OUTPUT
{{1,1},2,{1,1}} => 10
{1,{4,{6}}} => 27
{{1,1,1,1},{1,1,{2,2}},{1,{2,{3,3}}}} => 56
{1,{{13}}} => 40
The english version of the above code is something like:
For each item in
@str print it, print an arrow, print also the evaluation of the code resulting by joining strings obtained
modifying every one or more number (
\d+) or (
|) any singular character (
.) as follow: if the char is
{ then augment
$w by one and return
( instead of
{,
else if is a number return instead of it the string current
$w multiplying that number, else if the char is a
,return a
+ sign,else if
the char is
} lower
$w by one and return the string
), in any other case return the original string. Print also a newline.
Update: the assignement seems similar to
Re: Parsing a Tree to a Table.
HtH
L*
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.