Lex Posted August 9, 2007 Share Posted August 9, 2007 I found out about this website about a week ago , and now I'm watching the show . Congrats ! I saw the programming challenge , and decided to write a solution in perl . Since perl is a dynamic language , I decided to use dynamic coding . Sorry if I posted in the wrong topic ( and beeing one year late with the solution :) ) use strict; use warnings; sub generate_code { my $numbers=shift; my $total =shift; my $code; my $i; my @vars; for($i=0;$i<$numbers;$i++) { $code.="for(my $i${i}=1;$i${i}<$total;$i${i}++) {n"; push(@vars,"$i${i}"); } $code.="print ""; map { $code.="$_ " } @vars; $code.="n" "; $code.=condition(@vars,$total); for($i=0;$i<$numbers;$i++) { $code.="}n"; } $code; } sub condition { my @arr=@{ shift @_ }; my $number=shift; my $string="if("; for(my $i=0;$i<$#arr+1;$i++) { if($i==$#arr) { $string.="$arr[$i]==$number);"; last; } $string.="$arr[$i]+"; } $string; } my $num=shift || die "enter a number (n)n"; my $tot =shift || die "enter how many numbers should be added (k) n"; my $code=generate_code($tot,$num); eval($code); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.