changeset 1:b71457723bed

Added the two sum problem and a solution in Perl.
author Eris Caffee <discordia@eldalin.com>
date Fri, 01 May 2015 12:12:07 -0500
parents 129caa02df95
children 2a6239659909
files two_sum/nums1 two_sum/nums2 two_sum/two_sum.pl
diffstat 3 files changed, 59 insertions(+), 0 deletions(-) [+]
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/two_sum/nums1	Fri May 01 12:12:07 2015 -0500
     1.3 @@ -0,0 +1,10 @@
     1.4 +0
     1.5 +1
     1.6 +2
     1.7 +3
     1.8 +4
     1.9 +5
    1.10 +6
    1.11 +7
    1.12 +8
    1.13 +9
     2.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.2 +++ b/two_sum/nums2	Fri May 01 12:12:07 2015 -0500
     2.3 @@ -0,0 +1,10 @@
     2.4 +9
     2.5 +8
     2.6 +7
     2.7 +6
     2.8 +5
     2.9 +4
    2.10 +3
    2.11 +2
    2.12 +1
    2.13 +0
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/two_sum/two_sum.pl	Fri May 01 12:12:07 2015 -0500
     3.3 @@ -0,0 +1,39 @@
     3.4 +#!/bin/env perl
     3.5 +
     3.6 +use strict;
     3.7 +use warnings;
     3.8 +use Data::Dumper;
     3.9 +
    3.10 +# Problem: given an input array of numbers, and a target value, find two numbers
    3.11 +# in the input which sum to the target value.  Do so with worst case performance
    3.12 +# of O(N).
    3.13 +
    3.14 +# Solution: add the input numbers to a hash as they are read, with the number
    3.15 +# as the hash key, and it's index position in the input as the hash value.
    3.16 +
    3.17 +# At each step we can do an O(1) lookup in the hash to see if target - num has
    3.18 +# already been added to the hash.  If it has, we terminate processing and print
    3.19 +# the two numbers (along with their indices).  Otherwise we add num to the hash
    3.20 +# and loop back to read the next input number.
    3.21 +
    3.22 +# Usage: Pass the target value as a command line option, and the number array as
    3.23 +# values on stdin, one item per line.
    3.24 +
    3.25 +my $target = $ARGV[0];
    3.26 +my $lookfor;
    3.27 +my $num;
    3.28 +my $i = 0;
    3.29 +my %h;
    3.30 +while (<STDIN>) {
    3.31 +    $num = $_;
    3.32 +    chomp($num);
    3.33 +    $lookfor = $target - $num;
    3.34 +    if ( exists $h{$lookfor} ) {
    3.35 +        print "$num $lookfor (indices $i, ".$h{$lookfor}.")\n";
    3.36 +        exit(0);
    3.37 +    }
    3.38 +    $h{$num} = $i;
    3.39 +    $i++;
    3.40 +}
    3.41 +exit(1);
    3.42 +