Class: Euler::Solution

Inherits:
Object
  • Object
show all
Defined in:
lib/euler/solution.rb

Overview

This class represents a user created solution to a project Euler problem.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(problem, language) ⇒ Solution

Given the problem this solution is for an the language it’s implemented in initialize the instance.



18
19
20
21
22
23
24
25
# File 'lib/euler/solution.rb', line 18

def initialize problem, language
  if problem.is_a?(Problem)
    @problem = problem
  else
    @problem_id = problem
  end
  @language = language
end

Instance Attribute Details

#languageObject (readonly)

Returns the value of attribute language.



14
15
16
# File 'lib/euler/solution.rb', line 14

def language
  @language
end

Class Method Details

.allObject

Returns an array of all of the solutions



10
11
12
# File 'lib/euler/solution.rb', line 10

def self.all
  Euler.all_solutions_strategy
end

Instance Method Details

#answerObject

Returns this solution’s answer.



52
53
54
# File 'lib/euler/solution.rb', line 52

def answer
  problem.answer
end

#correct?Boolean

Alias for test.

Returns:

  • (Boolean)


74
75
76
# File 'lib/euler/solution.rb', line 74

def correct?
  test
end

#dirObject

Returns the directory assigned to this solution by calling Euler.directory_strategy.



80
81
82
# File 'lib/euler/solution.rb', line 80

def dir
  Euler.directory_strategy(self)
end

#initObject

Initialize this solution. This means:

  • run the create_directory_strategy to initialize the solutions

directory.

  • Run this solution’s language’s init method to do any extra

initialization steps required by the language.



43
44
45
46
47
48
49
# File 'lib/euler/solution.rb', line 43

def init
  mkdir
  if language_object.respond_to?(:init)
    language_object.init(self)
  end
  self
end

#problemObject

Returns the problem this solution is for.



28
29
30
# File 'lib/euler/solution.rb', line 28

def problem
  @problem ||= Problem.find(@problem_id)
end

#problem_idObject

Returns the id of the problem this solution is for.



33
34
35
# File 'lib/euler/solution.rb', line 33

def problem_id
  @problem_id ||= @problem.id
end

#resultObject

Alias for run.



62
63
64
# File 'lib/euler/solution.rb', line 62

def result
  run
end

#runObject

Returns the result of running this solution.



57
58
59
# File 'lib/euler/solution.rb', line 57

def run
  @result ||= (language_object.run(self) || '').gsub(/\r?\n/, '')
end

#testObject

Returns true if this solution is correct.



67
68
69
70
71
# File 'lib/euler/solution.rb', line 67

def test
  expected =  answer
  result   =  run
  expected == Digest::SHA1.hexdigest(result)
end