aboutsummaryrefslogtreecommitdiff
path: root/challenge-056/user-person/perl/ch-1.pl
blob: 5bc01d279de11fc0125a903c998546a49fb5d2be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env perl

###########################################################################
# script name: ch-1.pl                                                    #
#                                                                         #
# https://github.com/user-person                                          #
#                                                                         #
# https://perlweeklychallenge.org/blog/perl-weekly-challenge-056/         #
#                                                                         #
# Diff-K                                                                  #
# You are given an array @N of positive integers (sorted) and another     #
# non negative integer k.                                                 #
# Write a script to find if there exists 2 indices i and j such that      #
# A[i] - A[j] = k and i != j.                                             #
#                                                                         #
# It should print the pairs of indices, if any such pairs exist.          #
#                                                                         #
# Example:                                                                #
#                                                                         #
#         @N = (2, 7, 9)                                                  #
#         $k = 2                                                          #
#                                                                         #
# Output : 2,1                                                            #
#                                                                         #
###########################################################################

use strict;
use warnings;

my @n = (2, 7, 9);
my $k = 2;
my @match = ();

for (my $i = $#n;$i > 0; --$i) {

    my $diff = $n[$i] - $k;

    for (my $j = $i-1; $n[$j] >= $diff ; --$j) {
        if ($n[$j] == $diff && $i != $j) {
            push @match, "($i, $j)";
        }
    }
}

print "$_ " foreach reverse @match;
print "\n";

__END__
output:

(2, 1)