The objective is to implement a function that will return all pairs of integers from a given array of integers that have a difference of 2. The result array should be sorted in ascending order of values.
Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter.
Examples
[1, 2, 3, 4] --> [[1, 3], [2, 4]] [4, 1, 2, 3] --> [[1, 3], [2, 4]] [1, 23, 3, 4, 7] --> [[1, 3]] [4, 3, 1, 5, 6] --> [[1, 3], [3, 5], [4, 6]]
Tests
pairDifference([1,2,3,4])
pairDifference([1,3,4,6])
Happy coding!
This challenge comes from technikhil on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Discussion (18)
Python solution
Whoa, that reads almost as if it were English!
Thanks!
You mentioned in a recent comment that you're liearning Ruby, so here some tips:
pair_difference
Ruby has
each_with_object
for exactly this use case:C++ solution
Something like this should do it in JavaScript. I'm not entirely sure if this sort is okay, though. I can never remember which way it's ascendent and which descendent.
This really is Savage
There's were several Ruby solutions already, so I tried to come up with a different one:
Ruby solution
JS solution with reduce
My Swift solution :
JS solution
Took some iterations to get to this solution, but here it is.
Haskell:
JS Solution
output:
JavaScript
Assuming the input should be an array of unsigned integers.