Results 1 to 3 of 3

Thread: do something based on match in if statement

  1. #1
    Join Date
    Oct 2008
    Location
    Sweden
    Posts
    2,023
    Thanks
    17
    Thanked 319 Times in 318 Posts
    Blog Entries
    3

    Default do something based on match in if statement

    I have an if statement with three possible matches and depending on those matches, I want to do something. The code looks like this:
    Code:
    if (result1 == result2 & result2 == result3){
    	points = result1 + result2 + result3;
    } else if (result1 == result2 || result1 == result3 || result2 == result3){
    	//points should equal the sum of the match
    }
    If all three results are a match, the points should be the sum of them, however, if only two are a match, only the sum of those two should be the points. I know I could just use three if statements for the last part, but I'm just curious if it's possible to just use one.

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    As far as I can tell, you would have to have three if statements to replace:

    Code:
    //points should equal the sum of the match
    anyway, so may as well do without:

    Code:
    else if (result1 == result2 || result1 == result3 || result2 == result3)
    and have a total of four, instead of a total of five as would be required doing it the way you are trying.

    This might work, but using if/if else statements seems clearer, and could more easily be expanded to include more results:

    Code:
    if (result1 == result2 & result2 == result3){
    	points = result1 * 3;
    } else {
    	var results = [result1, result2, result3];
    	for(var i = 0; i < results.length; ++i){
    		for (var j = results.length - 1; j > -1; --j){
    			if(i !== j && results[i] == results[j]){
    				points = 2 * results[i];
    			}
    		}
    	}
    }
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Oct 2008
    Location
    Sweden
    Posts
    2,023
    Thanks
    17
    Thanked 319 Times in 318 Posts
    Blog Entries
    3

    Default

    Thanks John, I ended up using the first one. The second one is a bit too complicated for me right now, but hopefully I'll get it in a few weeks. (I'm taking Javascript )

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •