help needed with function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • boobikins
    New Member
    • May 2009
    • 5

    help needed with function

    Hi guys,

    I'm trying to complete a function that does the following:

    /* Tests if all balls selected match all balls drawn in the same order

    The function takes two arguments:
    an array of drawn balls
    an array of selected balls.

    The function code compares each ball in one array with the ball at the same position in the other array.

    The function returns:
    true if the arrays contain the same numbers in the same order
    false otherwise.
    */

    The code I have written is

    Code:
    	
    {
    for (var index = 0; index < drawnBalls.length; index = index + 1)
    	{
    		if(drawnBalls[index] == selectedBalls[index])
    		{
    		return true;
    		}
    		else
    		{
    		return false;
    		}
    	}
    
    }
    I have two arrays drawnBalls and selectedBalls, which will both be the same length and need to check if the numbers in the arrays match in the sameorder.
    Instead of returning an overall return of true or false if all the balls match, it is looping, giving me a separate result for each element. Can anyone give me some guidance on how to achieve my overall objective of, simply returning true if the values in the array are the same and in the same order, and false otherwise. Thanks in advance for any help.
  • SonECrocket
    New Member
    • Dec 2008
    • 3

    #2
    The best thing to due is use a variable in the loop. Then after the loop is done then return the variable. So the logic flows like this. First set the variable to false. Then loop through array setting variable to true if you have a match. If all elements in drawnBalls equall all elements in selectBalls. Then the variable will remain true. if any element doesn't match then set to false and break out of the for setting index to last value. This is due to the fact that if one element drawnBalls is not equal to selectBalls then the arrays are the same and you return false. Something like the following.

    Code:
    var match=new Boolean();
    for (var index = 0; index < drawnBalls.length; index = index + 1)
    	{
    		if(drawnBalls[index] == selectedBalls[index])
    		{
    		match=new Boolean(true);
    		}
    		else
    		{
    		match=new Boolean (false);
                                    index=drawnBalls.length;
    		}
    	}
    
    }
    return match.toString();
    Last edited by acoder; May 23 '09, 09:23 AM.

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      Although the idea is correct, the code could definitely be optimised. There's no need for a variable. If there is a non-match, just return false. If the loop ends and you're still in the function, that means that all values match, so return true at that point.

      Comment

      • boobikins
        New Member
        • May 2009
        • 5

        #4
        Trying again...

        Thanks for the reply both,

        I'm trying to amend my code to take into account both suggestions and have come up with:

        Code:
        var drawnBalls = [1,2,3,4,5];
        var selectedBalls = [1,2,3,4,5];
        
        document.write(drawnBalls + '<BR>');
        document.write(selectedBalls + '<BR>');
        
        function allBallsMatch(drawnBalls, selectedBalls)
        	
        	{
        	for (var index = 0; index < drawnBalls.length; index = index + 1)
        		{
        			if(drawnBalls [index] == selectedBalls[index])
        			{
        			return true;
        			}
        			else
        			{
        			return false;
        			
        				index=drawnBalls.length; 
        			}
        		
        		}
        	return true;
        	}
        This still doesn't seem to be giving me the required outcome, can you please point out where I'm going wrong?

        Comment

        • NitinSawant
          Contributor
          • Oct 2007
          • 271

          #5
          Hello boobikins,
          It seems that you are returning true/false every time you compare the elements of the array thats why its not working.. instead you can use a flag variable to point out that all elements in array match or not.


          Code:
          /*
          *                   ||  JAI BHAVANI ||
          */
          function allBallsMatch(drawnBalls, selectedBalls){
              var flag=true;
              for (var index = 0; index < drawnBalls.length; index = index + 1){
                      if(drawnBalls [index] == selectedBalls[index]){
                      	flag=true;
                      }
                      else{
                      	flag=false;
                      }
           
              }
              return flag;
          }
          i hope that, it works for you.

          kind regards,
          Nitin Sawant

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            Nitin, your code wouldn't work because, say, if it doesn't match the first one and matches the rest or even the last items, then it would return true.

            Comment

            • boobikins
              New Member
              • May 2009
              • 5

              #7
              I have never used flag, so how can I get my function to work returning an overall true or false? Still stuggling...

              Comment

              • gits
                Recognized Expert Moderator Expert
                • May 2007
                • 5390

                #8
                a flag is just a variable that holds a value for some easy comparison ... there are several ways to achieve your goal and a flag in your case would better hold a number ... acoder gave you a very good hint already ... so i'll repeat it and perhaps give you one more idea :) ... so let me write a working example in pseudocode:

                Code:
                var drawnBalls    = [1,2,3,4,5];
                var selectedBalls = [1,2,3,4,6];
                 
                function allBallsMatch(drawnBalls, selectedBalls) {
                    var dbl = drawnBalls.length;
                    var sbl = selectedBalls.length;
                
                    var compArray = [];
                
                    // or use a 'flag'
                    // var flag = 0;
                
                    if (dbl == sbl) {
                        for (var i = 0; i < dbl; ++i) {
                            var b = drawnBalls[i];
                
                            // in case b matches the number in selectedBalls
                            // push() something in the compArray or add 1 to 
                            // your flag
                            // else break; the loop 
                        }         
                    }
                
                    return compArray.length == dbl;
                
                    // or in case you have used the flag
                    // return flag == dbl;
                }
                kind regards

                Comment

                • omerbutt
                  Contributor
                  • Nov 2006
                  • 638

                  #9
                  Originally posted by gits
                  a flag is just a variable that holds a value for some easy comparison ... there are several ways to achieve your goal and a flag in your case would better hold a number ... acoder gave you a very good hint already ... so i'll repeat it and perhaps give you one more idea :) ... so let me write a working example in pseudocode:

                  Code:
                  var drawnBalls    = [1,2,3,4,5];
                  var selectedBalls = [1,2,3,4,6];
                   
                  function allBallsMatch(drawnBalls, selectedBalls) {
                      var dbl = drawnBalls.length;
                      var sbl = selectedBalls.length;
                  
                      var compArray = [];
                  
                      // or use a 'flag'
                      // var flag = 0;
                  
                      if (dbl == sbl) {
                          for (var i = 0; i < dbl; ++i) {
                              var b = drawnBalls[i];
                  
                              // in case b matches the number in selectedBalls
                              // push() something in the compArray or add 1 to 
                              // your flag
                              // else break; the loop 
                          }         
                      }
                  
                      return compArray.length == dbl;
                  
                      // or in case you have used the flag
                      // return flag == dbl;
                  }
                  kind regards
                  would it do the work as far i understood you want that all the indexes in both the arrays should have same values/ balls wotever else it should return false
                  see if this helps
                  Code:
                   function allBallsMatch(drawnBalls, selectedBalls)  
                       {
                  var flg=0;
                       for (var index = 0; index < drawnBalls.length; index = index + 1)
                           {
                               if(drawnBalls [index] != selectedBalls[index])
                               {
                                    flg=1;
                               }
                    
                           }
                           if(flg==0){
                             return true;
                            }else{
                             return false;
                           }
                       }

                  Comment

                  • gits
                    Recognized Expert Moderator Expert
                    • May 2007
                    • 5390

                    #10
                    have a look at post #6 ... the shown code has the same problem.

                    kind regards

                    Comment

                    • acoder
                      Recognized Expert MVP
                      • Nov 2006
                      • 16032

                      #11
                      On top of that, there's no need for any flags. You can just return false when there's definitely a non-match.

                      Comment

                      • omerbutt
                        Contributor
                        • Nov 2006
                        • 638

                        #12
                        Originally posted by gits
                        have a look at post #6 ... the shown code has the same problem.

                        kind regards
                        gits if this was for me then i dont think that i am returning true at any place iit would return false only if even any one of them would not match, but may be there is something wrong with it.

                        Comment

                        • gits
                          Recognized Expert Moderator Expert
                          • May 2007
                          • 5390

                          #13
                          yes ... i overlooked the braces ... so it would work ... it's just bad readable ... and as acoder said it would work but could be optimized to something like this (to avoid needless memory-usage and operations):

                          Code:
                          function allBallsMatch( drawnBalls, selectedBalls ) {
                              for ( var i = 0, l = drawnBalls.length; i < l; ++i ) {
                                  if ( drawnBalls[i] != selectedBalls[i] ) {
                                      return false;
                                  }
                              }
                              return true;
                          }

                          Comment

                          • NitinSawant
                            Contributor
                            • Oct 2007
                            • 271

                            #14
                            hi

                            Originally posted by acoder
                            Nitin, your code wouldn't work because, say, if it doesn't match the first one and matches the rest or even the last items, then it would return true.
                            Hello acoder,
                            thanks, now i got the mistake

                            Comment

                            • omerbutt
                              Contributor
                              • Nov 2006
                              • 638

                              #15
                              Originally posted by NitinSawant
                              Hello acoder,
                              actually the function which i posted works...

                              see the requirement of the user in first post, he wrote
                              "The function returns:
                              true if the arrays contain the same numbers in the same order
                              false otherwise."

                              here's sample code(which proves that its working correctly):
                              Code:
                              <!-- 
                                      ||    JAI BHAVANI    ||
                                      Author: Nitin Sawant
                                      Email: nitinsawant@netbeans.org
                              -->
                              <html>
                              <head>
                                  <script type="text/javascript">
                                      var drawnBalls = new Array(1,2,3,4,5);
                                      var selectedBalls = new Array(1,2,3,4,5);
                              	    function allBallsMatch(drawnBalls, selectedBalls){
                                          var flag=true;
                                          for (var index = 0; index < drawnBalls.length;index = index + 1){
                                                  if(drawnBalls [index] ==selectedBalls[index]){
                                                      flag=true;
                                                  }
                                                  else{
                                                      flag=false;
                                                  }
                                       
                                          }
                                          return flag;
                                      }
                                  </script>
                              </head>
                              <body>
                                  <script type="text/javascript"> 
                                      document.write("Contents of drawnBalls: <BR>");
                                      for(var temp=0;temp<drawnBalls.length;temp=temp+1){
                                          document.write(drawnBalls[temp]+ '<BR>');
                                      }
                                      document.write('<BR>');
                                      document.write("Contents of selectedBalls: <BR>");
                                      for(var temp1=0;temp1<selectedBalls.length;temp1=temp1+1){
                                          document.write(selectedBalls[temp1]+ '<BR>');
                                      }
                                      
                                      //check if both arrays are equal
                                      if(allBallsMatch(drawnBalls, selectedBalls)){
                                          document.write("All balls match <BR>");
                                      }else{
                                          document.write("All balls doesn't match <BR>");
                                      }
                                  </script>
                              </body>
                              </html>
                              suppose your very forst value in the array does not match and the rest all do it would set flag false for the first and then for all the rest values it would keep on setting the flag true :) isnt it , seee carefully
                              here is an example arrays with the elements try comparing these
                              Code:
                              drawnBalls [0,1,2,3,4,5]
                              selectedBalls[1,1,2,3,4,5]

                              Comment

                              Working...