aboutsummaryrefslogtreecommitdiff
path: root/challenge-088/andinus/README
blob: b372bec8d3f520d0df04e51dbfc8fae8b9fcc153 (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
                            ━━━━━━━━━━━━━━━
                             CHALLENGE 086

                                Andinus
                            ━━━━━━━━━━━━━━━


                               2020-11-15


Table of Contents
─────────────────

1. Task 1 - Pair Difference
.. 1. Perl





1 Task 1 - Pair Difference
══════════════════════════

  You are given an array of integers @N and an integer $A.

  Write a script to find find if there exists a pair of elements in the
  array whose difference is $A.

  Print 1 if exists otherwise 0.


1.1 Perl
────────

  • Program: <file:perl/ch-1.pl>

  @N & $A are taken from stdin, $A is the last argument.
  ┌────
  │ die "usage: ./ch-1.pl <integers \@N> <integer \$A>\n"
  │     unless scalar @ARGV >= 3;
  │
  │ my $A = pop @ARGV;
  │ my @N = @ARGV;
  └────

  We just loop over @N over a loop over @N & find the difference. If
  it's equal to `$A' or `-$A' then we print `1' & exit. The first loop
  is `shift''ing the numbers out of array `@N' because we are matching
  for both `$A' & `-$A' so we don't need the number again.

  For example, if `@N = [1, 2]' & we don't `shift' in first loop then
  we'll perform 2 subtraction operations: `1 - 2' & `2 - 1' & we won't
  have to match for `-$A' but if we just match for `-$A' then we can use
  `shift' & we'll only have to perform 1 subtraction operation `1 - 2'.

  We assume subtraction costs more than matching with `-$A', that makes
  this more efficient. But it doesn't matter much.
  ┌────
  │ while (my $int = shift @N) {
  │     foreach (@N) {
  │         my $diff = $int - $_;
  │         print "1\n" and exit 0 if ($diff == $A or $diff == -$A);
  │     }
  │ }
  │ print "0\n";
  │
  └────