The weekly challenge 290 - Task 1: Double Exist

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-290/#TASK1
 3 #
 4 # Task 1: Double Exist
 5 # ====================
 6 #
 7 # You are given an array of integers, @ints.
 8 #
 9 # Write a script to find if there exist two indices $i and $j such that:
10 #
11 ## 1) $i != $j
12 ## 2) 0 <= ($i, $j) < scalar @ints
13 ## 3) $ints[$i] == 2 * $ints[$j]
14 #
15 ## Example 1
16 ##
17 ## Input: @ints = (6, 2, 3, 3)
18 ## Output: true
19 ##
20 ## For $i = 0, $j = 2
21 ## $ints[$i] = 6 => 2 * 3 =>  2 * $ints[$j]
22 #
23 ## Example 2
24 ##
25 ## Input: @ints = (3, 1, 4, 13)
26 ## Output: false
27 #
28 ## Example 3
29 ##
30 ## Input: @ints = (2, 1, 4, 2)
31 ## Output: true
32 ##
33 ## For $i = 2, $j = 3
34 ## $ints[$i] = 4 => 2 * 2 =>  2 * $ints[$j]
35 #
36 ############################################################
37 ##
38 ## discussion
39 ##
40 ############################################################
41 #
42 # We just walk the array twice in nested loops. If the indices $i
43 # and $j are different and ints[$i] == 2 * ints[$j] we return True.
44 # Otherwise, we don't fulfill the condition with this pair and
45 # continue looping. If in the end, we didn't find any matching pair,
46 # we can return False.
47 
48 use strict;
49 use warnings;
50 
51 double_exist(6, 2, 3, 3);
52 double_exist(3, 1, 4, 13);
53 double_exist(2, 1, 4, 2);
54 
55 sub double_exist {
56    my @ints = @_;
57    print "Input: (", join(", ", @ints), ")\n";
58    foreach my $i (0..$#ints) {
59       foreach my $j (0..$#ints) {
60          next if $i == $j;
61          return print "Output: True\n" if $ints[$i] == 2 * $ints[$j];
62       }
63    }
64    print "Output: False\n";
65 }