我需要找到3个数组的解决方案,以解决a + b + c = 15(或其他问题)
到目前为止,我仍然坚持以下代码:
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
也许您有解决此问题的方法或解决此问题的方法。
答案 0 :(得分:5)
可能性的要素是元组。在此代码中,将每个都视为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
答案 1 :(得分:2)
另一个答案正确地诊断出您需要处理一个元组,而不是三个参数。
在Julia 1.0中,您也可以在lambda中使用argument destructuring,但是语法并不那么明显:
Iterators.filter(((a, b, c),) -> a + b + c == 15, possibilities)