The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.

Simple programming concept (For...Next) [SOLVED]

whuppinswhuppins Registered User regular
edited January 2008 in Help / Advice Forum
I'm keeping this abstract and language-ambiguous because I'm looking for information about the philosophy behind it, not necessarily the exact code to write. I want to implement the following logic:

For items 1 to n, perform a logical test on each item. If all tests are False, Path A is chosen. As soon as any test returns True, Path B is chosen.

Assuming the language has the standard set of DO, FOR, WHILE, EXIT, etc. statements, I'd like to identify the most elegant way to map this logic. I've come up with the following (pseudocode ahoy):
FOR x = 1 to 10
            IF x.flavor = "cherry" THEN GOTO path_b
        NEXT x
path_a:
        ...
        END
        ...
path_b:
        ...

As the saying goes, I know only enough about programming to be dangerous, so I know that using GOTO-type functions is generally inefficient and frowned upon where it's avoidable, though I don't know how to avoid it in this case. Is there a better solution that doesn't involve GOTO or excessive IF/THEN statements, and that only uses the most elementary of functions? This strikes me as a basic problem and I'm guessing there's a simple answer that will be obvious once someone points it out to me.

Thanks for any help.

whuppins on

Posts

  • Alistair HuttonAlistair Hutton Dr EdinburghRegistered User regular
    edited January 2008
    whuppins wrote: »
    I'm keeping this abstract and language-ambiguous because I'm looking for information about the philosophy behind it, not necessarily the exact code to write. I want to know the most elegant way to code the following logic:

    For items 1 to n, perform a logical test on each item. If all tests are False, Path A is chosen. As soon as any test returns True, Path B is chosen.

    Assuming the language has the standard set of DO, FOR, WHILE, EXIT, etc. statements, I'd like to identify the most elegant way to map this logic. I've come up with the following (pseudocode ahoy):
    FOR x = 1 to 10
                IF x.flavor = "cherry" THEN GOTO path_b
            NEXT x
    path_a:
            ...
            END
            ...
    path_b:
            ...
    

    As the saying goes, I know only enough about programming to be dangerous, so I know that using GOTO-type functions is generally inefficient and frowned upon where it's avoidable, though I don't know how to avoid it in this case. Is there a better solution that doesn't involve GOTO or excessive IF/THEN statements, and that only uses the most elementary of functions? This strikes me as a basic problem and I'm guessing there's a simple answer that will be obvious once someone points it out to me.

    Thanks for any help.

    You're pretty much there but you want to through in some hot subroutine action:
        SUBROUTINE Iterative_Check(array_of_things,check_value) RETURNS BOOLEAN
            FOR x = 1 to 10
                IF array_of_thing[x].flavor = check_value THEN RETURN TRUE
            NEXT x
            RETURN FALSE
        END SUBROUTINE
    
    IF Iterative_Check(an_array,"Sample Value") THEN
      //Path B
     ..
    ELSE
      //Path A
     ..
    

    Alistair Hutton on
    I have a thoughtful and infrequently updated blog about games http://whatithinkaboutwhenithinkaboutgames.wordpress.com/

    I made a game, it has penguins in it. It's pay what you like on Gumroad.

    Currently Ebaying Nothing at all but I might do in the future.
  • Jimmy KingJimmy King Registered User regular
    edited January 2008
    The best way depends on the context of the rest of the code. Your choices are:
    1) put path a and b inside your for loop and follow appropriately.
    2) create a variable and if the test returns true, set your variable to true value and exit the for loop. Then outside of the loop check the value of that variable to determine which you need to execute.

    Jimmy King on
  • ScrubletScrublet Registered User regular
    edited January 2008
    int flag = 1;
    int x = 1;

    while(flag && (x++ < 11))
    {
    /* If test fails, set flag to 0 and quit loop */
    if (TEST RETURNS FALSE)
    flag = 0;
    }
    /* All tests succeeded */
    if (flag)
    pathA;
    else pathB;

    Sorry after typing all this I remembered your philosophy statement and not asking for exact code. It's already up there but there's nothing that's rocket science in what I put.

    Scrublet on
    subedii wrote: »
    I hear PC gaming is huge off the coast of Somalia right now.

    PSN: TheScrublet
  • DrFrylockDrFrylock Registered User regular
    edited January 2008
    A simple but workable construction:
    boolean testPassed = false;
    for(int i = 0; i < 10; i++){
      if(pass(someTest)){
        testPassed = true;
        break;
      }
    }
    if(testPassed){
      doSomething();
    }
    else{
      doSomethingElse();
    }
    

    If you're a golfer, perhaps:
    boolean testPassed = false;
    for(int i = 0; (i < 10) && (!testPassed); i++){
      testPassed = pass(someTest);
    }
    if(testPassed){
      doSomething();
    }
    

    Or depending on how sophisticated your language lets your for loop be:
    boolean testPassed = false;
    for(int i = 0; (i < 10) && (!testPassed); i++, testPassed = pass(someTest)){}
    if(testPassed){
      doSomething();
    }
    else{
      doSomethingElse();
    }
    

    This of course assumes a more traditional language. If you were trying to be Pythonic or functional about it, you would probably define or find an operation that takes an iterator (or iterable) and a test, and then returns true if any of the items in that iterable pass the test (with short circuiting, of course).

    DrFrylock on
  • whuppinswhuppins Registered User regular
    edited January 2008
    OK, thanks for the prompt responses; I believe I have the idea. The only question that really jumps out at me is: Is it really better to create a variable than to use a goto or similar structure? Each posted solution has some subtle distinctions but the one thing they all have in common is the creation of a variable that's checked at the end of the tests. Is this use of variables really considered the most elegant way to do it? Knowing next to nothing about programming 'best practices', I assumed that giving the application another variable to remember would not be the ideal solution. Apparently I assumed wrong though?

    whuppins on
  • ScrubletScrublet Registered User regular
    edited January 2008
    Goto statements are vague and can get you into problems. In larger projects, they can make deciphering complicated code impossible. They could remove it from the language and lots of people would probaby breathe a sigh of relief. The variable is more easily understood and the overhead of adding one variable is negligible.

    Scrublet on
    subedii wrote: »
    I hear PC gaming is huge off the coast of Somalia right now.

    PSN: TheScrublet
  • HlubockyHlubocky Registered User regular
    edited January 2008
    Here is a note from wikipedia about the usage of GOTO:
    The GOTO statement has been the target of much criticism, the claim being that use of GOTO produces unreadable and generally unmaintainable "spaghetti code". As structured programming became more popular in the 1960s and 1970s, many computer scientists came to the conclusion that programs should always use so-called 'structured' flow-control commands such as loops and if-then-else statements in place of GOTO. However, others believed that[weasel words] use of GOTO did not unconditionally lead to poor quality code and that there are some tasks that cannot be straightforwardly accomplished in many programming languages without the use of one or more GOTO statements, such as implementing finite state machines, breaking out of nested loops and exception handling.

    Probably the most famous criticism of GOTO is a 1968 letter by Edsger Dijkstra called Go To Statement Considered Harmful [2] In that letter Dijkstra argued that unrestricted GOTO statements should be abolished from higher-level languages because they complicated the task of analyzing and verifying the correctness of programs (particularly those involving loops). An alternative viewpoint is presented in Donald Knuth's Structured Programming with go to Statements [3] which analyzes many common programming tasks and finds that in some of them GOTO is the optimal language construct to use.

    In this case, the small requirement of extra space on the stack for the test boolean outweighs the readability loss due to the goto.

    edit: oops, beated.

    Hlubocky on
  • RoundBoyRoundBoy Registered User regular
    edited January 2008
    without knowing the language involved .. the answer will depend.

    Usually a goto is NOT advised.. as you generally want to exit the loop for the exception, and return to continue processing. Unless you want to exit the loop entirely.. using your example you want to try it 10 times.. and when a condition is found.. stop processing the loop.

    The variable question is also language dependent too. In the example you posted in the OP, the goto label is still theoretically taking up memory space.. much the same way a variable would. But the ease of checking some variable against true / false is much better then the cost of the variable involved.. especially if you can reuse or garbage collect it later. Your example would leave the loop counter still in memory as you are technically still in the loop when you goto out of it.. unless you are using basic or something..

    Also in your example above... is the counting to 1-10 important? or just the loop until 'cherry' is found? A do..while loop is better for that purpose... especially for expansion of code later on.

    RoundBoy on
    sig_civwar.jpg
    Librarians harbor a terrible secret. Find it.
  • whuppinswhuppins Registered User regular
    edited January 2008
    OK, so after re-reading everything, I think the best thing to do is use a variable, "exit for", and if/then statement to route traffic rather than a goto, like so:
    passed = True
    for x = 1 to n
        if item(x).flavor = "cherry" then
            passed = False
            exit for
        end if
    next x
    
    if passed = True then sub_a else sub_b
    
    Is that about right?

    whuppins on
  • DocDoc Registered User, ClubPA regular
    edited January 2008
    whuppins wrote: »
    OK, so after re-reading everything, I think the best thing to do is use a variable, "exit for", and if/then statement to route traffic rather than a goto, like so:
    passed = True
    for x = 1 to n
        if item(x).flavor = "cherry" then
            passed = False
            exit for
        end if
    next x
    
    if passed = True then sub_a else sub_b
    
    Is that about right?

    Yeah.

    Doc on
This discussion has been closed.