Skip to content

Instantly share code, notes, and snippets.

@zoras
Last active June 18, 2021 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoras/cd06ba3d9f7351e7ab6a172d535299f9 to your computer and use it in GitHub Desktop.
Save zoras/cd06ba3d9f7351e7ab6a172d535299f9 to your computer and use it in GitHub Desktop.
source 'https://rubygems.org'
gem 'rspec'
GEM
remote: https://rubygems.org/
specs:
diff-lcs (1.4.4)
rspec (3.10.0)
rspec-core (~> 3.10.0)
rspec-expectations (~> 3.10.0)
rspec-mocks (~> 3.10.0)
rspec-core (3.10.1)
rspec-support (~> 3.10.0)
rspec-expectations (3.10.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.10.0)
rspec-mocks (3.10.2)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.10.0)
rspec-support (3.10.2)
PLATFORMS
x86_64-darwin-20
DEPENDENCIES
rspec
BUNDLED WITH
2.2.16
# frozen_string_literal: true
# Write a function which, given an array of integers of value greater or equal to 0, returns all unique pairs which
# sum to 100.
#
# Example data:
#
# input = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51]
# output = [[1,99], [0,100], [10,90], [51,49], [50,50]]
class UniquePair
def self.unique_pairs(numbers, sum=100)
Array(numbers)
.combination(2)
.map do |x, y|
x, y = y, x if x > y
[x, y] if x + y == sum
end.compact.sort.uniq || []
end
end
require 'rspec'
require './unique_pair'
RSpec.describe UniquePair do
describe '.unique_pairs' do
subject { described_class.unique_pairs(input) }
context 'when an array of numbers is provided' do
let(:input) { [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51] }
let(:output) { [[1,99], [0,100], [10,90], [49,51], [50,50]] }
it 'returns all unique pairs which sum up to 100' do
expect(subject).to match_array output
end
end
context 'when no input is provided' do
let(:input) { nil }
let(:output) { [] }
it 'returns an empty array' do
expect(subject).to match_array output
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment