1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-11-09 22:08:58 +01:00
programming-challenges/challenges/pairwise
2020-12-09 12:42:12 +01:00
..
solutions docs: fix typo 'at' should be 'on' 2020-09-12 22:15:21 +00:00
input-output.json Add "pairwise" challenge 2020-07-08 19:56:30 +02:00
README.md chore: ignore lockfiles + markdownlint 2020-12-09 12:42:12 +01:00

pairwise

Created by @Divlo on 8 July 2020.

Instructions

Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices.

You may use multiple pairs that have the same numeric elements but different indices. Each pair should use the lowest possible available indices. Once an element has been used it cannot be reused to pair with another element. For instance, pairwise([1, 1, 2], 3) creates a pair [2, 1] using the 1 at index 0 rather than the 1 at index 1, because 0+2 < 1+2.

For example pairwise([7, 9, 11, 13, 15], 20) returns 6. The pairs that sum to 20 are [7, 13] and [9, 11]. We can then write out the array with their indices and values.

Index 0 1 2 3 4
Value 7 9 11 13 15

Below we'll take their corresponding indices and add them.

  • 7 + 13 = 20 → Indices 0 + 3 = 3
  • 9 + 11 = 20 → Indices 1 + 2 = 3
  • 3 + 3 = 6 → Return 6

Examples

See the input-output.json file for examples of input/output.