Created
May 10, 2012 23:45
-
-
Save capncodewash/2656617 to your computer and use it in GitHub Desktop.
Countdown: an attempt at creating a 'Countdown'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Countdown.rb | |
# | |
# A lame attempt by someone who last used Ruby in the Paleolithic period (I think Perl was around then) to solve the Countdown problem ( http://rubyquiz.com/quiz7.html ). Bad habits from Python, PHP and various things are included. | |
# | |
# Attempted as a follow-up to the ScotRUG user group meeting coding kata. | |
# | |
# Will generate solutions for any combination of six integers. | |
# | |
# ©2012 Graeme West <[email protected]> | |
# Licensed under the Apache 2.0 licence ( http://www.apache.org/licenses/LICENSE-2.0 ). If you're into that kind of thing. | |
numbers = [100, 8, 4, 6, 7, 5] | |
operators = ["*","/","+","-"] | |
target = 108 | |
class Array | |
def random_element | |
self[rand(length)] | |
end | |
end | |
# A class to represent a possible result | |
class CountUp | |
attr_accessor :expression, :total, :delta | |
def initialize(expression, total, delta) | |
@expression = expression | |
@total = total | |
@delta = delta | |
end | |
def to_s | |
"Expression: %s\tTotal: %s\tDelta: %s" % [@expression, @total, @delta] | |
end | |
end | |
def assemble_expressions(numbers,operators,target) | |
haystack= [] | |
(2..6).each do |num_terms| | |
combs = numbers.permutation(num_terms).to_a | |
operator_combs = operators.permutation((num_terms - 1)).to_a | |
combs.uniq.each do |comb| | |
operator_combs.each do | operator_comb | | |
expr = comb[0].to_s() | |
comb[1..-1].each_with_index do |this_term, i| | |
expr += " " + operator_comb[i].to_s() + " " + this_term.to_s() | |
end | |
expr_total = eval(expr) | |
delta = target - expr_total | |
p = CountUp.new(expr, expr_total.to_s(), delta) | |
# 'haystack' should now contain every possible combination of operator and terms. | |
haystack << p | |
puts p.to_s() + "\n" # output them so that we can test the algorithm. 27480 lines, wahey! | |
end | |
end | |
end | |
return haystack | |
# puts haystack.to_s() # you might want to output it here I suppose. | |
end | |
results = assemble_expressions(numbers,operators,target) | |
# Pseudo-ruby-or-python-or-something code for cleanup and validation follows below. It's just a memory aide for when I actually write this. | |
# | |
# needles = [] | |
# results.each do {|i| return i if i.delta = 0} | |
# if needles.length > 0: | |
# puts needles | |
# exit | |
# else: # show the top 5 closest matches | |
# results.sort(delta).slice(:5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment