Skip to content

Instantly share code, notes, and snippets.

@belgoros
Last active July 28, 2022 06:01
Show Gist options
  • Save belgoros/8eca2dfebde876ac148eb1546c75ef02 to your computer and use it in GitHub Desktop.
Save belgoros/8eca2dfebde876ac148eb1546c75ef02 to your computer and use it in GitHub Desktop.
Exercisme: palindromes exercise
class Palindromes
private
attr_reader :factors, :max_factor, :min_factor, :palindromes
def initialize(min_factor: 1, max_factor: 1)
@min_factor = min_factor
@max_factor = max_factor
@factors = (min_factor..max_factor).to_a
@palindromes = palindromes
end
def pairs_by_product
factors.product(factors)
.uniq(&:sort)
.group_by { |f1, f2| f1 * f2 }
end
def palindrome?(number)
number.to_s == number.to_s.reverse
end
public
def generate_lazy
@palindromes = pairs_by_product.lazy
.map { |product, pairs| Product.new(product, pairs) }
.select(&:palindrome?)
end
def generate_no_lazy
@palindromes = pairs_by_product
.map { |product, pairs| Product.new(product, pairs) }
.select(&:palindrome?)
end
def palindromes
pairs_by_product
.map { |product, pairs| Product.new(product, pairs) }
.select(&:palindrome?)
end
def generate_initalize_memo
@palindromes = pairs_by_product
.map { |product, pairs| Product.new(product, pairs) }
.select(&:palindrome?)
end
def smallest
palindromes.min
end
def largest
palindromes.max
end
end
class Product
include Comparable
private
def initialize(value, factors)
@value = value
@factors = factors
end
public
attr_reader :value, :factors
def palindrome?
value.to_s.reverse == value.to_s
end
def <=>(other)
value <=> other.value
end
end
if $PROGRAM_NAME == __FILE__
require 'benchmark/ips'
gwl = Palindromes.new
gwol = Palindromes.new
gmim = Palindromes.new
#gim = Palindromes.new
Benchmark.ips do |x|
x.report('generate with lazy') { gwl.generate_lazy }
x.report('generate without lazy') { gwol.generate_no_lazy }
x.report('generate memoized in method') { gmim.palindromes }
#x.report('generate initialize_memo') { gim.generate_initalize_memo }
x.compare!
end
end
@kotp
Copy link

kotp commented Jul 28, 2022

Sent an RFC (Request for Comment) patch to you for this, so that you can apply it to this repository (I, of course, have no access and so can not do so directly, but can if you apply the patch(es).)

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