Skip to content

Instantly share code, notes, and snippets.

@temirov
Created May 3, 2016 17:54
Show Gist options
  • Save temirov/5c3d67aafbf32056c2ae2fdaaf867eaf to your computer and use it in GitHub Desktop.
Save temirov/5c3d67aafbf32056c2ae2fdaaf867eaf to your computer and use it in GitHub Desktop.
An object evolutional mutator
class Life
attr_reader :object, :methods, :arguments, :result
def initialize(object:, methods:, arguments:, result:)
@object, @methods, @arguments, @result = object, methods, arguments, result
end
def evolve
(1..max_length).each do |size|
method_chains(size).each do |method_chain|
mutation = mutate(method_chain)
return method_chain if mutation == result
end
end
end
private
def object
@object.dup
end
def method_chains(size)
permuted_methods(size: size).product(permuted_arguments(size: size))
end
def mutate(method_chain)
args = method_chain[0].zip(method_chain[1])
args.inject(object) { |o, a| o.send(*a) rescue nil }
end
def max_length
[@methods, @arguments].max{ |a,b| a.length <=> b.length }.count
end
def permuted_methods(size:)
@methods.repeated_permutation(size).to_a
end
def permuted_arguments(size:)
@arguments.repeated_permutation(size).to_a
end
end
transcode = Life.new(
object: "\xAE",
methods: %i{encode force_encoding},
arguments: [::Encoding::UTF_8, ::Encoding::ISO_8859_1],
result: "®"
)
transcode.evolve
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment