Skip to content

Instantly share code, notes, and snippets.

@Sam-Serpoosh
Created November 14, 2012 05:09
Show Gist options
  • Save Sam-Serpoosh/4070404 to your computer and use it in GitHub Desktop.
Save Sam-Serpoosh/4070404 to your computer and use it in GitHub Desktop.
Closest to zero! Just a short program for fun!
class Closest
MAX = 2000000000000
def to_zero(input)
raise IllegalArgumentException if input.nil? || input.empty?
closest_to_zero = MAX
@least_distance = MAX
input.each do |num|
if closer_to_zero(num)
@least_distance = num.abs
closest_to_zero = num
elsif positive_of_closest_to_zero_exist?(num)
closest_to_zero = num
end
end
closest_to_zero
end
def closer_to_zero(num)
num.abs < @least_distance
end
def positive_of_closest_to_zero_exist?(num)
num.abs == @least_distance && num > 0
end
end
class IllegalArgumentException < Exception
end
require_relative "closest_to_zero"
describe Closest do
it "throws IllegalArgumenException when input is nil" do
lambda do
subject.to_zero(nil)
end.should raise_error(IllegalArgumentException)
end
it "throws IllegalArgumentException when input is empty" do
expect do
subject.to_zero([])
end.to raise_error(IllegalArgumentException)
end
it "returns the only number when there is one element" do
subject.to_zero([1]).should == 1
end
it "returns closer number to zero between 2 numbers" do
subject.to_zero([2, 1]).should == 1
end
it "returns closer nubmer to zero between multiple numbers" do
subject.to_zero([2, 3, 1, 4]).should == 1
end
it "returns negative number which is closer to zero" do
subject.to_zero([2, -1, 3, 4]).should == -1
end
it "returns closest negative number to zero" do
subject.to_zero([-1, -5, 3, 2]).should == -1
end
it "returns positive when negative & positive of same distance to zero exist" do
subject.to_zero([-1, 1]).should == 1
subject.to_zero([1, -1]).should == 1
end
it "returns the closest number to zero" do
subject.to_zero([1, -2, 3, -1, -5, 5, 2]).should == 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment