Skip to content

Instantly share code, notes, and snippets.

@TheMadHau5
Last active April 27, 2020 20:05
Show Gist options
  • Save TheMadHau5/aede8236f5eee0993cf31220854ec249 to your computer and use it in GitHub Desktop.
Save TheMadHau5/aede8236f5eee0993cf31220854ec249 to your computer and use it in GitHub Desktop.
With a given input of an expression, this code solves for the bracket-ing that results in the highest result.
def getmax nums, ops, dbg=0, &f
# f is action performed on numbers before comparing (like taking absolute value)
maxn = nil
pat = nil
(0...ops.size).to_a.permutation do |p| # iterate over each possible pattern
begin
n = solve(nums, ops, p, dbg - 1) # attempt to solve (based on given pattern)
if n.infinite?
n = nil
raise ZeroDivisionError, "divided by 0"
end
rescue StandardError => e # on error
STDERR.puts "#{e.class}: #{e.message}" # log errors
end
if dbg > 0
p([nums, ops, p, n, f.(n)]) # debug output
end
if maxn.nil? || (!n.nil? && f.(n) > f.(maxn)) # checks for new maximum
maxn = n
pat = p
end
end
return [maxn, pat] # answer (number, brackets)
end
def solve nums, ops, pat, dbg=0
if ops.size != pat.size || nums.size - 1 != ops.size # validate input
raise
end
nums, ops, pat = nums.dup, ops.dup, pat.dup # copy input (ruby uses references)
while i = pat.shift # iterates through the pattern
nums[i, 2] = nums[i].send(ops.delete_at(i), nums[i + 1]) # flattening (perform operation)
pat.map! { |x| x > i ? x - 1 : x } # fix pattern (so stuff doesn't break)
if dbg > 0
p([nums, ops, pat]) # debug output
end
end
return nums[0] # final answer
end
# eg (15 ÷ 3 - 2 + 5 - 20 ÷ 2 × 7 - 19 + 9 + 6 ÷ 2 ^ 2):
# getmax([15, 3, 2, 5, 20, 2, 7, 19, 9, 6, 2, 2], %i[/ - + - / * - + + / **]) { |num| num.abs }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment