Skip to content

Instantly share code, notes, and snippets.

@danielmciotti
Created April 11, 2024 04:02
Show Gist options
  • Save danielmciotti/bfccb2c6c9f9bbba55bfa26263abc0c2 to your computer and use it in GitHub Desktop.
Save danielmciotti/bfccb2c6c9f9bbba55bfa26263abc0c2 to your computer and use it in GitHub Desktop.
strategy tutorial
class BaseContext
attr_accessor :strategy
def initialize(strategy)
@strategy = strategy
end
def execute(*args)
@strategy.new.execute(*args).round(2)
end
end
class AverageStrategy
def execute(grades)
grades.sum(0.0) / grades.size
end
end
class WeightedStrategy
WEIGHTS = [0.1, 0.1, 0.2, 0.3, 0.3]
def execute(grades)
[grades, WEIGHTS].transpose.map { |weight_and_grade| weight_and_grade.inject(:*) }.sum
end
end
class AllButLowerStrategy
def execute(grades)
AverageStrategy.new.execute(grades.max(grades.size - 1))
end
end
class HighestPairStrategy
def execute(grades)
AverageStrategy.new.execute(grades.max(2))
end
end
rand_grades = ->(num_grades) { num_grades.times.map { (rand * 100).round(2) } }
dataset = {
paul: rand_grades.call(5),
duncan: rand_grades.call(5),
leto: rand_grades.call(5),
wang_miao: rand_grades.call(5),
da_shi: rand_grades.call(5),
luo_ji: rand_grades.call(5)
}
apply_strategy = ->(dataset, context) { dataset.to_h { |student, grades| [student, context.execute(grades)] } }
context = BaseContext.new(AverageStrategy)
strategies = [WeightedStrategy, AllButLowerStrategy, HighestPairStrategy]
answer_matrix = { "AverageStrategy" => apply_strategy.call(dataset, context) }
strategies.map do |next_strategy|
context.strategy = next_strategy
answer_matrix[next_strategy.to_s] = apply_strategy.call(dataset, context)
end
ap dataset
ap answer_matrix
answer_matrix.each do |strategy, data|
ap "#{strategy} - Passing grades: #{data.select { |_student, grade| grade >= 60.0 }}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment