How to resolve the algorithm Minimal steps down to 1 step by step in the Julia programming language

Published on 22 June 2024 08:30 PM

How to resolve the algorithm Minimal steps down to 1 step by step in the Julia programming language

Table of Contents

Problem Statement

Given: The goal is find the minimum number of steps necessary to reduce N down to one. At any step, the number may be:

There may be many ways to reduce the initial N down to 1. Your program needs to:

No divisors, D. a single subtractor of 1. Single divisor of 2; single subtractor of 1: Divisors 2 and 3; subtractor 1: Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1: Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Minimal steps down to 1 step by step in the Julia programming language

The provided Julia code defines a function called findshortest that uses a breadth-first search to find the shortest path from a start number to a goal number, given a set of actions and a failure condition. It also defines functions for finding the maximum shortest path and for testing the findshortest function with different parameters. Here's a detailed explanation of the code:

  1. Structs:

    • Action: Represents an action, which is a function that takes two arguments (i, x) and returns a new number.
    • ActionOutcome: Represents the outcome of an action, including the action performed and the resulting number.
  2. Printing Function:

    • Customizes the printing behavior for ActionOutcome objects to display the action, input, and output.
  3. memoized Variable:

    • A dictionary that stores memoized results to avoid recomputation.
  4. findshortest Function:

    • Parameters:
      • start: Starting number.
      • goal: Goal number.
      • fails: Failure condition function that takes a number and returns true if the number fails the condition.
      • actions: Dictionary of actions, mapping action names to arrays of arguments for each action.
      • verbose: Boolean indicating whether to print verbose information.
      • maxsteps: Maximum number of steps to search for the shortest path.
    • Algorithm:
      • Initializes solutions to store solutions and numsteps to 0.
      • Starts with a sequence containing only the starting number.
      • If the starting number is equal to the goal, it returns 0.
      • Iteratively searches for shorter paths by exploring all possible actions and their outcomes:
        • For each sequence in the current set of sequences, it tries all possible actions and arguments.
        • If an action doesn't fail, it adds the new action outcome to the sequence and checks if the new number is equal to the goal.
        • If the new number is the goal, it stores the sequence in the solutions vector.
        • Otherwise, it adds the sequence to a vector of new sequences to explore in the next iteration.
      • If verbose is enabled, it prints the shortest solution found.
      • Memoizes the result in the memoized dictionary and returns the minimum number of steps needed to reach the goal.
  5. failed Function:

    • Failure condition function that checks if a number is less than 1.
  6. divisors Variable:

    • An array of divisors used as arguments for the divide action.
  7. divide Function:

    • An action that divides a number by a divisor.
  8. subtractors1 and subtractors2 Variables:

    • Arrays of subtractors used as arguments for the subtract action.
  9. subtract Function:

    • An action that subtracts a subtractor from a number.
  10. actions1 and actions2 Variables:

    • Dictionaries of actions:
      • actions1 uses divisors for divide and subtractors1 for subtract.
      • actions2 uses divisors for divide and subtractors2 for subtract.
  11. findmaxshortest Function:

    • Parameters:
      • g: Goal number.
      • fails: Failure condition function.
      • acts: Dictionary of actions.
      • maxn: Maximum starting number to consider.
    • Algorithm:
      • Computes the number of steps needed to reach the goal for each starting number from 1 to maxn using findshortest.
      • Finds the maximum number of steps and the starting numbers that require this maximum number of steps.
      • Prints the maximum number of steps and the corresponding starting numbers.
  12. teststeps Function:

    • Parameters:
      • g: Goal number.
      • fails: Failure condition function.
      • acts: Dictionary of actions.
      • maxes: Array of maximum starting numbers to consider.
    • Algorithm:
      • Tests the findshortest function with different parameters and prints the results. It finds the shortest path from 1 to 10 and the maximum shortest path for different maximum starting numbers.
  13. Testing and Output:

    • The code tests findshortest with different goal numbers, action dictionaries, and maximum starting numbers.
    • It prints the shortest paths found and the maximum shortest paths for the specified parameters.

In summary, this code provides a framework for finding the shortest path from a start number to a goal number using a breadth-first search, taking into account actions and failure conditions. It also includes functions for finding the maximum shortest path and for testing the shortest path finder with different parameters.

Source code in the julia programming language

import Base.print
 
struct Action{T}
    f::Function
    i::T
end
 
struct ActionOutcome{T}
    act::Action{T}
    out::T
end
 
Base.print(io::IO, ao::ActionOutcome) = print(io, "$(ao.act.f) $(ao.act.i) yields $(ao.out)")
 
memoized = Dict{Int, Int}()
 
function findshortest(start, goal, fails, actions, verbose=true, maxsteps=100000)
    solutions, numsteps = Vector{Vector{ActionOutcome}}(), 0
    seqs = [ActionOutcome[ActionOutcome(Action(div, 0), start)]]
    if start == goal
        verbose && println("For start of $start, no steps needed.\n")
        return 0
    end
    while numsteps < maxsteps && isempty(solutions)
        newsequences = Vector{Vector{ActionOutcome}}()
        numsteps += 1
        for seq in seqs
            for (act, arr) in actions, x in arr
                result = act(seq[end].out, x)
                if !fails(result)
                    newactionseq = vcat(seq, ActionOutcome(Action(act, x), result))
                    numsteps == 1 && popfirst!(newactionseq)
                    if result == goal
                        push!(solutions, newactionseq)
                    else
                        push!(newsequences, newactionseq)
                    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
        seqs = newsequences
    end
    if verbose
        l = length(solutions)
        print("There ", l > 1 ? "are $l solutions" : "is $l solution", 
            " for path of length ", numsteps, " from $start to $goal.\nExample: ")
        for step in solutions[1]
            print(step, step.out == 1 ? "\n\n" : ", ")
        end
    end
    memoized[start] = numsteps
    return numsteps
end
 
failed(n) = n < 1
 
const divisors = [2, 3]
divide(n, x) = begin q, r = divrem(n, x); r == 0 ? q : -1 end
 
const subtractors1, subtractors2 = [1], [2]
subtract(n, x) = n - x
 
actions1 = Dict(divide => divisors, subtract => subtractors1)
actions2 = Dict(divide => divisors, subtract => subtractors2)
 
function findmaxshortest(g, fails, acts, maxn)
    stepcounts = [findshortest(n, g, fails, acts, false) for n in 1:maxn]
    maxs = maximum(stepcounts)
    maxstepnums = findall(x -> x == maxs, stepcounts)
    println("There are $(length(maxstepnums)) with $maxs steps for start between 1 and $maxn: ", maxstepnums)
end
 
function teststeps(g, fails, acts, maxes)
    println("\nWith goal $g, divisors $(acts[divide]), subtractors $(acts[subtract]):")
    for n in 1:10
        findshortest(n, g, fails, acts)
    end
    for maxn in maxes
        findmaxshortest(g, fails, acts, maxn)
    end
end
 
teststeps(1, failed, actions1, [2000, 20000, 50000])
empty!(memoized)
teststeps(1, failed, actions2, [2000, 20000, 50000])


  

You may also check:How to resolve the algorithm Sorting algorithms/Counting sort step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm Hofstadter Q sequence step by step in the APL programming language
You may also check:How to resolve the algorithm Dijkstra's algorithm step by step in the REXX programming language
You may also check:How to resolve the algorithm Rep-string step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Keyboard input/Flush the keyboard buffer step by step in the DCL programming language