我需要找到解决 a + b + c = 15(或其他)的 3 个数组的解决方案
到目前为止,我坚持使用以下代码:
A = 1:10
B = 1:10
C = 1:10
possibilities = Iterators.product(A, B, C)
solutions = Iterators.filter((a, b, c) -> a + b + c == 15, possibilities)
sol = collect(solutions)
for (a, b, c) in sol
println(a, " ", b, " ", c)
end
我从编译器得到这个错误:
> ERROR: LoadError: MethodError: no method matching
> (::##1#2)(::Tuple{Int64,Int64,Int64}) Closest candidates are:
> #1(::Any, !Matched::Any, !Matched::Any) at /home/cg/root/7729001/main.jl:6 Stacktrace: [1] start_filter(::##1#2,
> ::Base.Iterators.Prod{UnitRange{Int64},Base.Iterators.Prod2{UnitRange{Int64},UnitRange{Int64}}})
> at ./iterators.jl:272 [2] _collect(::UnitRange{Int64},
> ::Base.Iterators.Filter{##1#2,Base.Iterators.Prod{UnitRange{Int64},Base.Iterators.Prod2{UnitRange{Int64},UnitRange{Int64}}}},
> ::Base.HasEltype, ::Base.SizeUnknown) at ./array.jl:408 [3]
> collect(::Base.Iterators.Filter{##1#2,Base.Iterators.Prod{UnitRange{Int64},Base.Iterators.Prod2{UnitRange{Int64},UnitRange{Int64}}}})
> at ./array.jl:397 while loading /home/cg/root/7729001/main.jl, in
> expression starting on line 7
也许您有解决此问题的想法或解决问题的方法。
最佳答案
可能性的元素是元组。在此代码中将每个视为 x
:
A = 1:10
B = 1:10
C = 1:10
possibilities = Iterators.product(A, B, C)
# The change is in this line
solutions = Iterators.filter(x -> x[1] + x[2] + x[3] == 15, possibilities)
sol = collect(solutions)
for (a, b, c) in sol
println(a, " ", b, " ", c)
end
关于filter - Julia 迭代器乘积和过滤器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52656716/