Printing out a Random Array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Energizer100
    New Member
    • Nov 2007
    • 60

    #31
    Originally posted by JosAH
    Simply iterate (loop) over the array; if you see a non-zero number then print it,
    otherwise skip it (i.e. do nothing).

    kind regards,

    Jos

    One of the assignment rules is
    Do not solve the problem by printing out only the non-zero values in the array

    Comment

    • Laharl
      Recognized Expert Contributor
      • Sep 2007
      • 849

      #32
      Originally posted by Energizer100
      wouldn't that just switch the array around?

      for example

      1 0 0 2 3 4 5 6 7 8 0 9 2 1 4 6 0 4 // regular array
      1 4 0 2 3 4 5 6 7 8 6 9 2 1 4
      Yup. If you want them actually taken out, loop through, count how many zeroes there are, and make a new array with the number of nonzero elements in the original. Then feed all the nonzero elements into that array and print.

      Comment

      • Energizer100
        New Member
        • Nov 2007
        • 60

        #33
        1. Write a program that creates an array of random integers. Use a constant for the size of the array.

        2. Write a method compact that removes all zeroes from the array, leaving the order of the other elements unchanged. All local variables within this function must be scalar. In other words, you may not use a second array to solve the problem.

        3. Do not solve the problem by printing out only the non-zero values in the array. The compact method must remove all zeros from the array.

        Comment

        • Energizer100
          New Member
          • Nov 2007
          • 60

          #34
          Originally posted by Energizer100
          1. Write a program that creates an array of random integers. Use a constant for the size of the array.

          2. Write a method compact that removes all zeroes from the array, leaving the order of the other elements unchanged. All local variables within this function must be scalar. In other words, you may not use a second array to solve the problem.

          3. Do not solve the problem by printing out only the non-zero values in the array. The compact method must remove all zeros from the array.

          I have an idea, but i don't know how to put it in. After it prints out the first random array. The method, Compact, will run as a for loop. then each element goes through a cleaner method and returns the cleaned element, cleaning meaning it will get rid of zeros. So if it is a zero, it will be equal to null. But I don't know how to type that...

          and what's wrong with this code?

          Code:
          import java.util.Arrays;
          
          public class Compact 
          {
          
          	public static int[] randomArray(int[] n)
          	{
          		for (int i = 0; i < n.length; i++)
          			{
          				int b = (int) (Math.random() * 100);
          				n[i] = b;
          				return n[i];
          			}
          	}
          		
          	/*	for (int i = 0; i < a.length; i++)
          			{
          				
          			}
          */
          public static void main(String args[])
          {
          	int a[] = new int[20];
          	
          	System.out.print(randomArray(a) + " ");
          }		
          }

          Comment

          • Laharl
            Recognized Expert Contributor
            • Sep 2007
            • 849

            #35
            That doesn't work, as null is not an integer, so it can't be put into an array of integers. If you used Integers, this will work, as an Integer is an object, and thus can be null.

            Frankly, I don't think this actually is possible, as to the best of my knowledge, arrays have static size determined at creation, which then can't be changed. Thus, you can't actually remove elements from an array. You can make them into something that gets skipped over based on your code (null), or shove them to one end.

            Also, your printing code is still wrong. That will print out the address of the returned array, not the array itself. Call System.out.prin tln(randomArray (a).toString()) instead.

            Comment

            • JosAH
              Recognized Expert MVP
              • Mar 2007
              • 11453

              #36
              Use System.arraycop y() each time you 'see' a zero; copy the rest of the
              array one element to the 'left'; keep a counter each time you do that and print
              all the elements again except for the last 'count' elements.

              kind regards,

              Jos

              Comment

              • Energizer100
                New Member
                • Nov 2007
                • 60

                #37
                Originally posted by JosAH
                Use System.arraycop y() each time you 'see' a zero; copy the rest of the
                array one element to the 'left'; keep a counter each time you do that and print
                all the elements again except for the last 'count' elements.

                kind regards,

                Jos
                This is my code so far.

                Code:
                import java.util.Arrays;
                
                public class Compact 
                {
                	public static void main(String args[])
                	{
                		int a[] = new int[20];
                		int sum = 0;
                		
                		for (int i = 0; i < a.length; i++)
                			{
                				int b = (int) (Math.random() * 10);
                				a[i] = b;
                				System.out.print(a[i] + " ");
                			}
                		
                		System.out.println();
                		
                		for (int k = 0; k < a.length; k++)
                			{
                				if (a[k] == 0)
                				{
                					a[k] = a[k + 1];
                					sum++;
                				}
                			}
                		
                		for (int j = 0; j < a.length - sum; j++)
                			{
                				System.out.print(a[j] + " ");
                			}
                	}	
                }
                The problem I'm having now is that the position where the zero was will be filled by the next number. But the next number will still be there, i need it to go down, or disappear..

                Comment

                • Laharl
                  Recognized Expert Contributor
                  • Sep 2007
                  • 849

                  #38
                  To swap two values in an array, you have to create a dummy variable to hold one of the values.

                  [CODE=java]
                  int temp = a[i];
                  a[i]=a[i+1];
                  a[i+1]=temp;
                  [/CODE]

                  To "remove" your zeroes and shove them to one end, you can use the method Jos suggested (Google it for more details). Your code is a good start for a different way to do it, but by swapping each zero with a[a.length-sum], as long as that value is not zero, (if it is, increment sum until you don't have a zero or you get back to the current value), your printing loop should work fine.

                  Comment

                  • JosAH
                    Recognized Expert MVP
                    • Mar 2007
                    • 11453

                    #39
                    w.r.t. this hackery, also read a little article I wrote in the 'Howtos' section named
                    'Old tricks' (or similar). IMHO the OP should start to learn programming because
                    there's nothing Java specific about moving array elements around.

                    kind regards,

                    Jos

                    Comment

                    • Energizer100
                      New Member
                      • Nov 2007
                      • 60

                      #40
                      Okay, i got it working but there is one problem

                      Code:
                      import java.util.Arrays; //Imports Array Package
                      
                      public class Compact //Creates Class Compact
                      {
                      	public static void main(String args[]) //Main Method
                      	{
                      		/*Variables*/
                      		int a[] = new int[20];
                      		int sum = 0;
                      		
                      		/*First for loop prints out the random array*/
                      		for (int i = 0; i < a.length; i++)
                      			{
                      				int b = (int) (Math.random() * 10);
                      				a[i] = b;
                      				System.out.print(a[i] + " ");
                      			}
                      		
                      		/*Prints out a blank line*/
                      		System.out.println();
                      		
                      		/*Second for loop returns the random array without zeros*/
                      		for (int k = 0; k < a.length - 1; k++)
                      			{
                      				if (a[k] == 0)
                      				{
                      					for (int m = k; m < a.length - 1; m++)
                      					{
                      						for (int n = 0; n < a.length - 1; n++)
                      						{
                      						}
                      					}
                      					sum++;
                      				}
                      			}
                      		
                      		//Prints out the array without zeros
                      		for (int j = 0; j < a.length - sum; j++)
                      			{
                      				System.out.print(a[j] + " ");
                      			}
                      	}	
                      }
                      What I'm trying to do in the second for loop is found out if the next integer is a zero, then I'll remove them...But I don't know how.
                      For example

                      1 0 0 2 3 4 <--Initial Array
                      1 2 3 4 <--Compact Array

                      but my code will output this

                      1 0 2 3 4

                      because it takes the next integer. So i need something that will check whether or not the next integer is a zero...

                      Comment

                      • Laharl
                        Recognized Expert Contributor
                        • Sep 2007
                        • 849

                        #41
                        You can use [i+1] to access the next element in the array, but you will need to make sure that you don't go out of bounds.

                        Comment

                        • Energizer100
                          New Member
                          • Nov 2007
                          • 60

                          #42
                          Originally posted by Laharl
                          You can use [i+1] to access the next element in the array, but you will need to make sure that you don't go out of bounds.

                          I don't exactly know where and how to put it.

                          Comment

                          • Energizer100
                            New Member
                            • Nov 2007
                            • 60

                            #43
                            Originally posted by Energizer100
                            I don't exactly know where and how to put it.
                            I tried doing it, but I'm getting an out of bounds error

                            Code:
                            import java.util.Arrays; //Imports Array Package
                            
                            public class Compact //Creates Class Compact
                            {
                            	public static void main(String args[]) //Main Method
                            	{
                            		/*Variables*/
                            		int a[] = new int[20];
                            		int sum = 0;
                            		
                            		/*First for loop prints out the random array*/
                            		for (int i = 0; i < a.length; i++)
                            			{
                            				int b = (int) (Math.random() * 10);
                            				a[i] = b;
                            				System.out.print(a[i] + " ");
                            			}
                            		
                            		/*Prints out a blank line*/
                            		System.out.println();
                            		
                            		/*Second for loop returns the random array without zeros*/
                            		for (int k = 0; k < a.length - 1; k++)
                            			{
                            				if (a[k] == 0)
                            				{
                            					//It needs to check if the next integer is zero. If it is
                            					//then it needs to go to the next one.
                            					for (int i = 1; i < a.length - 1; i++)
                            					{
                            						if (a[k + i] == 0)
                            						{
                            							a[k] = a[k + i + 1];
                            						}
                            						else
                            						{
                            							a[k] = a[k + 1];
                            						}
                            					}
                            					sum++;
                            				}
                            			}
                            		
                            		//Prints out the array wihtout zeros
                            		for (int j = 0; j < a.length - sum; j++)
                            			{
                            				System.out.print(a[j] + " ");
                            			}
                            	}	
                            }

                            Comment

                            • Laharl
                              Recognized Expert Contributor
                              • Sep 2007
                              • 849

                              #44
                              You have to check if k+i (or k+i+1) < a.length to use that method. You also have some logical issues in the assignment code, as the value from farther in the array is not swapped down to the original location of the 0.

                              It's a start, though. Also, to be efficient, you don't need to loop through the entire array in the inner loop, as the parts of the array you've already seen can be known to not be zero, so you can start from i=k.

                              Comment

                              • Energizer100
                                New Member
                                • Nov 2007
                                • 60

                                #45
                                Originally posted by Laharl
                                You have to check if k+i (or k+i+1) < a.length to use that method. You also have some logical issues in the assignment code, as the value from farther in the array is not swapped down to the original location of the 0.

                                It's a start, though. Also, to be efficient, you don't need to loop through the entire array in the inner loop, as the parts of the array you've already seen can be known to not be zero, so you can start from i=k.
                                I'm not sure I follow. Sorry, I'm still new at Java.

                                Code:
                                import java.util.Arrays; //Imports Array Package
                                
                                public class Compact //Creates Class Compact
                                {
                                	public static void main(String args[]) //Main Method
                                	{
                                		/*Variables*/
                                		int a[] = new int[20];
                                		int sum = 0;
                                		
                                		/*First for loop prints out the random array*/
                                		for (int i = 0; i < a.length; i++)
                                			{
                                				int b = (int) (Math.random() * 10);
                                				a[i] = b;
                                				System.out.print(a[i] + " ");
                                			}
                                		
                                		/*Prints out a blank line*/
                                		System.out.println();
                                		
                                		/*Second for loop returns the random array without zeros*/
                                		for (int k = 0; k < a.length - 1; k++)
                                			{
                                				if (a[k] == 0)
                                				{
                                					//It needs to check if the next integer is zero. If it is
                                					//then it needs to go to the next one.
                                					for (int i = k; i < a.length; i++)
                                					{
                                						if (a[k + i] == 0)
                                						{
                                							if (a[k + i + 1] < a.length);
                                							a[k] = a[k + i + 1];
                                						}
                                						else
                                						{
                                							a[k] = a[k + 1];
                                						}
                                					}
                                					sum++;
                                				}
                                			}
                                		
                                		//Prints out the array wihtout zeros
                                		for (int j = 0; j < a.length - sum; j++)
                                			{
                                				System.out.print(a[j] + " ");
                                			}
                                	}	
                                }
                                Would it be something like that?

                                Comment

                                Working...