Minimal steps down to 1: Difference between revisions

Content deleted Content added
Wherrera (talk | contribs)
m second stretch goal
Wherrera (talk | contribs)
m memoize
Line 187: Line 187:


=={{header|Julia}}==
=={{header|Julia}}==
Non-recursive solution that is memoized for the count-only ortions of the task. When the steps are to be printed, the solution is not memoized in order to list all possible paths of the shortest length (all solutions). Implemented as a generic solution for any functions acting on an integer and taking any range of second arguments, with the goal solution also specifiable. To do so generically, it is also necessary to specify a falure condition, which in the example is falling below 1.
Non-recursive, non-memoized. Implemented as a generic solution for any functions acting
on an integer and taking any range of second arguments, with the goal solution also specifiable.
To do so generically, it is also necessary to specify a falure condition, which in the example
is falling below 1.
<lang julia>import Base.print
<lang julia>import Base.print


Line 206: Line 203:
print(io, "$(ao.act.f) $(ao.act.i) yields $(ao.out)")
print(io, "$(ao.act.f) $(ao.act.i) yields $(ao.out)")
end
end

memoized = Dict{Int, Int}()


function findshortest(start, goal, fails, actions, verbose=true, maxsteps=100000)
function findshortest(start, goal, fails, actions, verbose=true, maxsteps=100000)
Line 217: Line 216:
newsequences = Vector{Vector{ActionOutcome}}()
newsequences = Vector{Vector{ActionOutcome}}()
numsteps += 1
numsteps += 1
for seq in seqs, (act, arr) in actions, x in arr
for seq in seqs
result = act(seq[end].out, x)
for (act, arr) in actions, x in arr
if !fails(result)
result = act(seq[end].out, x)
newactionseq = vcat(seq, ActionOutcome(Action(act, x), result))
if !fails(result)
numsteps == 1 && popfirst!(newactionseq)
newactionseq = vcat(seq, ActionOutcome(Action(act, x), result))
if result == goal
numsteps == 1 && popfirst!(newactionseq)
push!(solutions, newactionseq)
if result == goal
else
push!(solutions, newactionseq)
push!(newsequences, newactionseq)
else
push!(newsequences, newactionseq)
end
end
end
end
if !verbose && isempty(solutions) &&
all(x -> haskey(memoized, x[end].out), newsequences)
minresult = minimum(x -> memoized[x[end].out], newsequences) + numsteps
memoized[start] = minresult
return minresult
end
end
end
end
Line 240: Line 247:
end
end
end
end
memoized[start] = numsteps
return numsteps
return numsteps
end
end
Line 272: Line 280:


teststeps(1, failed, actions1, [2000, 20000, 50000])
teststeps(1, failed, actions1, [2000, 20000, 50000])
empty!(memoized)
teststeps(1, failed, actions2, [2000, 20000, 50000])
teststeps(1, failed, actions2, [2000, 20000, 50000])
</lang>{{out}}
</lang>{{out}}