Skip to content

Instantly share code, notes, and snippets.

@vbrazo
Last active January 4, 2018 17:19
Show Gist options
  • Save vbrazo/5a5267aac7d4993b5ef3cc67b7dd824a to your computer and use it in GitHub Desktop.
Save vbrazo/5a5267aac7d4993b5ef3cc67b7dd824a to your computer and use it in GitHub Desktop.
Leap Year Algorithm Exam

Given a year, report if it is a leap year.

The tricky thing here is that a leap year in the Gregorian calendar occurs:

  • on every year that is evenly divisible by 4
  • except every year that is evenly divisible by 100
  • unless the year is also evenly divisible by 400

For example, 1997 is not a leap year, but 1996 is. 1900 is not a leap year, but 2000 is.

If your language provides a method in the standard library that does this look-up (like Ruby Date.new(2000).leap?) pretend it doesn't exist and implement it yourself.

@vbrazo
Copy link
Author

vbrazo commented Jan 4, 2018

leap_year.rb

class LeapYear
  def initialize(year)
    @year = year
  end

  attr_reader :year

  def leap?
    divisible_by_four && (!divisible_by_one_hundred || divisible_by_four_hundred)
  end

  private

  def divisible_by_four
    year % 4 == 0
  end

  def divisible_by_one_hundred
    year % 100 == 0
  end

  def divisible_by_four_hundred
    year % 400 == 0
  end
end

leap_year_spec.rb

require_relative 'leap_year'

describe LeapYear do
  describe '.leap?' do
    subject { described_class.new(year) }

    context 'given the 1996 leap year' do
      let(:year) { 1996 }

      it '1996 returns true' do
        expect(subject.leap?).to be true
      end
    end

    context 'given the 2000 leap year' do
      let(:year) { 2000 }

      it '2000 returns true' do
        expect(subject.leap?).to be true
      end
    end

    context 'given 1997 that is not a leap year' do
      let(:year) { 1997 }
      
      it '1997 returns false' do
        expect(subject.leap?).to be_falsey
      end
    end

    context 'given 1900 that is not a leap year' do
      let(:year) { 1900 }

      it '1900 returns false' do
        expect(subject.leap?).to be_falsey
      end
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment