Skip to content

Instantly share code, notes, and snippets.

@yurivish
Last active August 8, 2019 01:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save yurivish/497f328019472e17616d32edb358bc61 to your computer and use it in GitHub Desktop.
using Combinatorics
factorial(x) = reduce(*, 1:Int(x))
# type union shorthand for dispatching on specific functions
union(fs...) = Union{typeof.(fs)...}
# unary operations
apply!(op::union(sqrt, factorial), xs) = push!(xs, op(pop!(xs)))
# binary operations
apply!(op::union(+, -, *, ÷, ^), xs) = push!(xs, op(pop!(xs), pop!(xs)))
function exec!(ops, nums)
for op in ops
# bail out if we're over 10,000, taking the square root of a
# negative number, or computing too large a factorial
num = last(nums)
abs(num) > 10_000 && break
op == sqrt && num < 0 && break
op == factorial && (num < 0 || num > 10 || !isinteger(num)) && break
# otherwise, apply the next operation
apply!(op, nums)
end
last(nums)
end
function go(ops, nums)
for ops in permutations(ops), nums in permutations(nums)
result = exec!(ops, copy(nums))
if result 2019
println("Nums: $(reverse(nums)) \n Ops: $(ops)")
# break
end
end
end
go(
[+, -, *, ÷, ^, sqrt, factorial],
[2.0, 3, 4, 6, 8, 9]
)
# (sqrt(factorial(3 + 2) ÷ 8) ^ 4) * 9 - 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment