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
Python solution
Whoa, that reads almost as if it were English!
Thanks!
Ruby solution
There's were several Ruby solutions already, so I tried to come up with a different one:
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
Took some iterations to get to this solution, but here it is.
Haskell:
JS solution with reduce
My Swift solution :
JS Solution
output:
JavaScript
Assuming the input should be an array of unsigned integers.
JS solution
Ruby solution
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:could not be grateful anymore!!!
very thankful
hope to learn more from you.
really thanks!