Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Difference in classes?

Options
  • 01-09-2011 7:13pm
    #1
    Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,092 Mod ✭✭✭✭


    Hello I am messing around with two classes here, seemingly quite identical, but the output of one differs from the other. They both sort 10 'random' numbers but the second class always has three 0's first, and does not sort completely correctly? What is going on?
    import java.util.Random;
    public class SortNumbers {
      
      public static void sort(int[] num) {
        
        for (int i = 0; i < num.length; i++) {
          int min = i; 
          
          for (int j = i; j < num.length; j++) {
            if (num[j] < num[min])
            {
              min = j;
              }
          }
         
          int tmp;
          tmp = num[i];
          num[i] = num[min];
          num[min] = tmp;
        }
      }
    
      
      public static void main(String[] args) {
    
        int[] nums = new int[10]; 
        Random r = new Random();
    
        for (int i = 0; i < nums.length; i++)
       
              nums[i] = r.nextInt(100);
              sort(nums); 
        for (int i = 0; i < nums.length; i++)
         
              System.out.println(nums[i]);
      }
    }
    

    import java.util.Random;
    public class sorting {
      
      public static void sort(int[] num) {
        
        for (int i = 0; i < num.length; i++) {
          int min = i; 
          
          for (int j = i; j < num.length; j++) {
            if (num[j] < num[min])
            {
              min = j;
              }
          }
       
          int tmp;
          tmp = num[i];
          num[i] = num[min];
          num[min] = tmp;
        }
      }
    
       public static void main(String[] args) {
        int[] nums = new int[10]; 
        Random r = new Random();
        for (int i = 0; i < nums.length; i++)
          
              nums[i] = r.nextInt(100);
              sort(nums); // Sort them
    
        for (int i = 0; i < nums.length; i++)
          
          System.out.println(nums[i]);
      }
    }
    


Comments

  • Registered Users Posts: 7,863 ✭✭✭The_B_Man


    You seem to be missing opening and closing brackets { } after the 2nd last for() loop in both classes.
    So it must be a problem with "sort()".


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,092 Mod ✭✭✭✭Tar.Aldarion


    Hmm odd, I thought that would work. The same thing happens when i add brackets.

    The weird thing is how the first program works fine and the second does not. I am blind but I don't see a difference.


  • Closed Accounts Posts: 709 ✭✭✭Robdude


    I used a text comparison tool (winMerge is a good free one, but for simple stuff you can use http://www.textdiff.com/)

    There are very few differences. The name of the class, the number of spaces before the 2nd 'public' method and the number of return lines before the System.Out line.

    Those three are all I can see.


  • Closed Accounts Posts: 9,139 ✭✭✭-Trek-


    The only thing I spot is that every time you put a number in the array you call the sort method, is there a reason for that?
    Whereas you could fill the array first and then call the sort method.
    I changed up the sort method here, if its wrong I can only put it down to needing sleep, anyway (apologises for indentation) ...
    import java.util.Random;
    public class SortItOut {
      
    	public static void sort(int[] num) {
    		int array[] = num;
    		int temp;
    		for (int i = 0; i < array.length; i++)
    		{
    			for (int z = i+1; z < array.length; z++)
    			{
    				if (array[z] < array[i])
    				{
    					temp = array[i];
    					array[i] = array[z];
    					array[z] = temp;
    				}
    			}
    		}
    	}
    
    	public static void main(String[] args) {
    		int[] nums = new int[10]; 
    		Random r = new Random();
    		//fill the array first
    		for (int i = 0; i < nums.length; i++)
    		{ 
    			nums[i] = r.nextInt(100);
    		}   
    		//sort them    
    		sort(nums);
    		//then print em
    		for (int i = 0; i < nums.length; i++)
    		{   
    			System.out.println(nums[i]); 
    		}	
    	 
    	}
     
    }
    

    hope its of help


  • Closed Accounts Posts: 709 ✭✭✭Robdude


    -Trek- wrote: »
    The only thing I spot is that every time you put a number in the array you call the sort method, is there a reason for that?
    Whereas you could fill the array first and then call the sort method.
    I changed up the sort method here, if its wrong I can only put it down to needing sleep, anyway (apologises for indentation) ...
    import java.util.Random;
    public class SortItOut {
      
    	public static void sort(int[] num) {
    		int array[] = num;
    		int temp;
    		for (int i = 0; i < array.length; i++)
    		{
    			for (int z = i+1; z < array.length; z++)
    			{
    				if (array[z] < array[i])
    				{
    					temp = array[i];
    					array[i] = array[z];
    					array[z] = temp;
    				}
    			}
    		}
    	}
    
    	public static void main(String[] args) {
    		int[] nums = new int[10]; 
    		Random r = new Random();
    		//fill the array first
    		for (int i = 0; i < nums.length; i++)
    		{ 
    			nums[i] = r.nextInt(100);
    		}   
    		//sort them    
    		sort(nums);
    		//then print em
    		for (int i = 0; i < nums.length; i++)
    		{   
    			System.out.println(nums[i]); 
    		}	
    	 
    	}
     
    }
    

    Only problem with the code is it doesn't deal with duplicates

    I'm new to Java - but in his original example I thought
       public static void main(String[] args) {
        int[] nums = new int[10]; 
        Random r = new Random();
        for (int i = 0; i < nums.length; i++)
          
              nums[i] = r.nextInt(100);
              sort(nums); // Sort them
    

    sort(nums); would only execute once. The indenting might be misleading, but without {}'s the for loop should only apply to the next statement (nums = r.nextInt(100);

    At least, that was my understanding. If I'm wrong let me know :)


  • Advertisement
  • Closed Accounts Posts: 9,139 ✭✭✭-Trek-


    Yeah, still learn myself :) but think your right, the indention is misleading, by all means I'm open to correction.


  • Moderators, Technology & Internet Moderators Posts: 1,334 Mod ✭✭✭✭croo


    Hello I am messing around with two classes here, seemingly quite identical, but the output of one differs from the other. They both sort 10 'random' numbers but the second class always has three 0's first, and does not sort completely correctly? What is going on?
    ...
    With the exception of whitespace & class names both are exactly the same. And both worked as they should for me.


  • Registered Users Posts: 2,021 ✭✭✭ChRoMe


    Run clean before build and it will probably sort it.


  • Closed Accounts Posts: 577 ✭✭✭Galtee


    Robdude is correct, the sort will only execute once as the first statement after the for will be evaluated if braces are omitted once the guard in the loop is satisfied so in theory you could write something like

    string[] idxparity = new string[10]
    for
    (int i=0; i<10;i++)
    if (i%2==0)
    idxparity =
    "Even";
    else
    idxparity = "Odd";

    and it's still vaild without the braces although not very nice to look at.

    I had a look at this issue last night. I don't have a java IDE but the logic looks fine and if applying same algorithm with ported differences in c# it works fine also.
    The only thing I'd look at if there is an actual problem would be the random number generator, it may not be functioning properly and the 0s mentioned as part of the output may well be the default array values so if you declare an array of int, don't fill it and then output it you'll get all zeros as it's initialized with 0s. array of strings is array of nullls, array of float is array of 0s etc. so maybe the array positions are not being filled properly by the random number gen.
    The only other thing then could be the context in which the classes are running, ie is there any possibility that the sort being called isn't the actual sort that defined in that class, ie is there another sort routine available in the context of the program? Just questions I'd be asking if I had an issue with it, after that I'm blank, apart from the couple of minor inefficiencies in the sorting algorithm. :)


  • Closed Accounts Posts: 9,139 ✭✭✭-Trek-


    ^Thats interesting, thanks for that, you learn something new everyday.


  • Advertisement
  • Registered Users Posts: 1,311 ✭✭✭Procasinator


    The "always" is important here regarding the three zeroes. How many runs have you made to determine always?

    It has a low probability, but it is possible that three zeroes could be randomly generated (note nextInt(n) will generate 0 >= x < n, not 1 to n). That this would happen more than once in a row is also unlikely, but possible.

    A Random generator could be affected by the seed, but you should be using Java's default in both code listings, which is based off the time at execution.


  • Closed Accounts Posts: 577 ✭✭✭Galtee


    The "always" is important here regarding the three zeroes. How many runs have you made to determine always?

    It has a low probability, but it is possible that three zeroes could be randomly generated (note nextInt(n) will generate 0 >= x < n, not 1 to n). That this would happen more than once in a row is also unlikely, but possible.

    A Random generator could be affected by the seed, but you should be using Java's default in both code listings, which is based off the time at execution.

    I would hazard a guess that the seed is supposed to be reset everytime nextInt is called, if not then it would return the same number if using the same algorithm based on the seed would it not?


  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    Galtee wrote: »
    I would hazard a guess that the seed is supposed to be reset everytime nextInt is called, if not then it would return the same number if using the same algorithm based on the seed would it not?
    I don't think so. The seed is set initially before the first use, then nextInt continues along a predictive algorithm using the original seed.

    Resetting the seed every time removes the pseudo randomness of the generator. The numbers are taken from a uniform distribution. The distribution cannot be the same if the seed is modified every time.

    Resetting the seed each time to the same value should cause the same nextInt value each time.

    Correct me if I'm wrong but I believe this is how it works in most languages.


  • Closed Accounts Posts: 577 ✭✭✭Galtee


    Webmonkey wrote: »
    I don't think so. The seed is set initially before the first use, then nextInt continues along a predictive algorithm using the original seed.

    Resetting the seed every time removes the pseudo randomness of the generator. The numbers are taken from a uniform distribution. The distribution cannot be the same if the seed is modified every time.

    Resetting the seed each time to the same value should cause the same nextInt value each time.

    Correct me if I'm wrong but I believe this is how it works in most languages.

    You're spot on, it does. Based on the original seed it generates a sequence of numbers, using the same seed will generate the same sequence of numbers each time and these are then returned with the call to next etc.


  • Registered Users Posts: 1,311 ✭✭✭Procasinator


    Galtee wrote: »
    I would hazard a guess that the seed is supposed to be reset everytime nextInt is called, if not then it would return the same number if using the same algorithm based on the seed would it not?

    Generally not. The sequence generated will be the same per seed when using the same algorithm, unless designed to not to be the case. But the nextInt will get the next integer in the sequence, not the same integer again.

    It's actually often said to have a negative effect on randomness when you reseed a PNRG. Interesting StackOverflow question:
    http://stackoverflow.com/questions/976993/issues-with-seeding-a-pseudo-random-number-generator-more-than-once


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,092 Mod ✭✭✭✭Tar.Aldarion


    thanks guys, that site to compare is handy too.

    i re-wrote it a few times this morning in the same class with the same result....i made a new class and it works just fine. :confused:


  • Registered Users Posts: 1,922 ✭✭✭fergalr


    thanks guys, that site to compare is handy too.

    i re-wrote it a few times this morning in the same class with the same result....i made a new class and it works just fine. :confused:

    Everyone has had this happen them a few times.

    Something in your toolchain is caching the old version, and running that. Worth trying to make it so your tools don't do such things, and worth being suspicious of IDEs when strange things are happening.

    The right solution is to make sure your toolchain can't fool you like this.

    But a wrong solution, that often helps (if you come to someone elses setup, say) is to stick a new print statement in with the code you are changing, and make sure it prints out.


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,092 Mod ✭✭✭✭Tar.Aldarion


    sounds good to me thanks, i am a lover of the print out statements too heh.


  • Registered Users Posts: 1,922 ✭✭✭fergalr


    sounds good to me thanks, i am a lover of the print out statements too heh.

    Me too.

    In fact, they are often my primary debugging tool.

    I'm just trying to make it look like they aren't, and that really my unit tests and debugging tools catch all my errors, to maintain an illusion of professionalism.


  • Registered Users Posts: 2,021 ✭✭✭ChRoMe


    fergalr wrote: »
    Everyone has had this happen them a few times.

    Something in your toolchain is caching the old version, and running that. Worth trying to make it so your tools don't do such things, and worth being suspicious of IDEs when strange things are happening.

    The right solution is to make sure your toolchain can't fool you like this.

    But a wrong solution, that often helps (if you come to someone elses setup, say) is to stick a new print statement in with the code you are changing, and make sure it prints out.

    Your build scripts should be setup to do this automatically.


  • Advertisement
  • Registered Users Posts: 1,922 ✭✭✭fergalr


    ChRoMe wrote: »
    Your build scripts should be setup to do this automatically.

    To put a print statement in your code? Presumably not?

    You mean that your build scripts should be setup in such a way to not cache classes compiled from code that has changed? Yes, of course they should - or rather, of course whatever toolchain you are using, should be setup so as that it picks up on changes properly.

    But the problem is that sometimes, even though toolchains should do this, they sometimes don't.

    One quick way to test for such problems, is the quick and dirty print statement.

    I did explicitly say that the right solution is to make sure the toolchain can't cause these problems - but I've seen similar problems in numerous different developer setups, and if someone brought me over to look at a bug, its something I'd check - not immediately, but if stuff wasn't making sense.


  • Registered Users Posts: 2,021 ✭✭✭ChRoMe


    fergalr wrote: »
    To put a print statement in your code? Presumably not?

    You mean that your build scripts should be setup in such a way to not cache classes compiled from code that has changed? Yes, of course they should - or rather, of course whatever toolchain you are using, should be setup so as that it picks up on changes properly.

    But the problem is that sometimes, even though toolchains should do this, they sometimes don't.

    One quick way to test for such problems, is the quick and dirty print statement.

    I did explicitly say that the right solution is to make sure the toolchain can't cause these problems - but I've seen similar problems in numerous different developer setups, and if someone brought me over to look at a bug, its something I'd check - not immediately, but if stuff wasn't making sense.

    Yeah things break from time to time in the chain. However the instances of this catching someone out drop dramatically with good build scripts, I think printing out to the console is everyone's dirty secret :)

    I always do a find for any messages before commit anything to the repo.


Advertisement