Last active
August 8, 2019 01:09
-
-
Save yurivish/497f328019472e17616d32edb358bc61 to your computer and use it in GitHub Desktop.
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
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