Jump to content

Perl solution to season 1 episode 6 programming challenge


Lex
 Share

Recommended Posts

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);

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...