Re: Re[2]: Return from nested subroutines (still goto discussion)

new topic     » goto parent     » topic index » view thread      » older message » newer message

> Now the purpose of the program is to search d so that sum(d) = 10 and
> every element of d is from 0 to 3. But when a solution is found, it
> will just print the first solution found and continue to printing
> "program end".
> 
> Now how can it modified to use no GOTO and no decrease on performance?
> (using  flags  to  indicate  whether  a  solution has been found would
> decrease performance, I think)

Does this work? I got x = 5 and y = 3. The trick is to use functions
and pass down a 'success' value, like here I use 1 for success, 0 for
failure. Whenever there is a success (or 1) I exit the current loop
and/or return. I've actually gotten used to this style of coding and I
prefer it over goto. This just seems more logical that jumping around
code all willy-nilly.

sequence d
    d = {0,0,0,0,0}

function sum( sequence x )
-- calculate the sum of
-- all values in x
atom val
    val = 0
    for i = 1 to length(x) do
        val += x[i]
    end for
    return val
end function

function r(integer x, integer y)
    d[x] = y
    if x = 5 then
        if sum(d) = 10 then
            printf(1, "x = %d\ny = %d\n", {x,y})
            puts(1, "success\n")
            return 1
        end if
    else
        for i = 0 to 3 do
            if r(x+1, i) then
                return 1
            end if
        end for
    end if

    return 0
end function

procedure main()
    for i = 0 to 3 do
        if r(1, i) then
            exit
        end if
    end for

    puts(1, "program end\n")
end procedure

main()


new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu