Results 1 to 13 of 13
  1. #1
    Cod
    Cod is offline Member
    Join Date
    Nov 2009
    Location
    Honolulu, HI
    Posts
    59
    Rep Power
    0

    Default Find the First Negative Number of an Array

    The code I came up with works if there is only one negative number. If there is more than one negative number, I get a throw exception. Which portion of the code should I be focusing on? Or is there another loop statement needed?

    Java Code:
          for (int i = 0; i < a.length; i++) {
           if (a[i] < 0)
             negativeNumbers ++;
          }
         
          int j = a.length - 1;
         
          while (j >= 0) {
           if (a[j - negativeNumbers] < 0) {
             a[j] = 0;
             a[j - 1] = a[j - negativeNumbers];
             negativeNumbers--;
             j--;
            }
           else
            a[j] = a[j - negativeNumbers];
            j--;
          }
    Any guidance is greatly appreciated.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    If there is more than one negative number, I get a throw exception. Which portion of the code should I be focusing on?

    The bit that's wrong!

    To try and isolate which bit that might be, construct a small runnable program that shows this behaviour. Post both the code and the runtime exception (the entire stack trace).

    -------------------

    Also it will help if you could clarify: are you trying to find something in the array (as the thread title states), or change the array as the code is doing?
    Last edited by pbrockway2; 02-20-2011 at 04:17 AM.

  3. #3
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    It's not clear what you're trying to do, but this looks like trouble:
    Java Code:
        for (int i = 0; i < a.length; i++) {
            if (a[i] < 0)
                negativeNumbers ++;
        }
         
        int j = a.length - 1;
         
        while (j >= 0) {
            if (a[j - negativeNumbers] < 0) {
                a[j] = 0;
                a[j - 1] = a[j - negativeNumbers];
                negativeNumbers--;
                [COLOR="Blue"]j--;[/COLOR]
            }
            else
                a[j] = a[j - negativeNumbers];
            [COLOR="Blue"]j--;[/COLOR]
        }
    I've cleaned up your indentation. Note that within your while loop, if the if condition is true you end up decrementing j twice.

    -Gary-

  4. #4
    Cod
    Cod is offline Member
    Join Date
    Nov 2009
    Location
    Honolulu, HI
    Posts
    59
    Rep Power
    0

    Default

    Quote Originally Posted by pbrockway2 View Post
    The bit that's wrong!
    Also it will help if you could clarify: are you trying to find something in the array (as the thread title states), or change the array as the code is doing?
    The goal is to find out if an array has a negative integer. If it does, the program is meant to place a 0 (zero) in the index right after the first negative number and shift subsequent elements to the right, dropping the last element. If there is no negative number, the program should return the original array.

    So, to answer your question, the code is trying to find and change.

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    THanks.

    Since you are only finding the first negative value and altering the array from that point on it makes no sense at all to be counting the number of negative values as you do in the first loop.

    You should remove this loop and any other code involving this variable.

    the program is meant to place a 0 (zero) in the index right after the first negative number and shift subsequent elements to the right, dropping the last element

    As stated this doesn't make sense. I think you mean shift all elements after the negative one to the right, not those subsequent to the one that was set to zero (because that would leave the slot to the right of the zero without a value.)

    Think about how you would try to do this and express your plan in plain English before writing code.

  6. #6
    Cod
    Cod is offline Member
    Join Date
    Nov 2009
    Location
    Honolulu, HI
    Posts
    59
    Rep Power
    0

    Default

    Starting from scratch again...

    I have the following code to place a zero after a negative number.
    Java Code:
         for (int i = 0; i < a.length; i++) {
           if (a[i] < 0)
             a[i + 1] = 0;
         }
    The problem is, it puts a zero behind all negative numbers and takes the place of the element that was directly after the negative number (if it existed).

    I cannot figure out / understand how to tell the program to stop going through the motions once it finds the first negative number. Also, I cannot figure out how to shift all the elements after the negative one to the right.

    Any further guidance is greatly appreciated.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Java Code:
    for (int i = 0; i < a.length; i++) {
        if (a[i] < 0) {
            //a[i + 1] = 0;
            
            // put code here to work down the array from
            // i+1 to the end changing the values.
        }
    }

    The code you use will probably involve another for loop since you are walking down the rest of the array. It may also involve another variable since you have to remember each value you replace so you can use that the next time around the loop.

    Again: a precise and clearly expressed plan of attack will help you. Try doing the task yourself with a strip of paper, a pencil and an eraser. You erase a number and write zero, and then what? You need the number you just erased so it can be put in the next slot.

  8. #8
    Cod
    Cod is offline Member
    Join Date
    Nov 2009
    Location
    Honolulu, HI
    Posts
    59
    Rep Power
    0

    Default

    It's safe to say, now I'm lost. I thought I had it with my first go around (counting the negatives, etc.), but obviously that didn't work for multiple negatives. I've been working in my spiral notebook for 45-mins now and can't come up with anything except for this...

    Java Code:
         
         int j = 0;
         
         for (int i = 0; i < a.length; i++) {
           if (a[i] < 0) {
             j = a[i + 1];
             a[i + 1] = 0; }
         }

    After testing the method, temp gives me the correct numbers which zero takes place of; however, I still don't know how to shift the numbers following the zero to the right without copying the array (which isn't allowed). Also, I still haven't figured out how to keep the zero behind the first negative number only.

    Thanks for all the help pbrockway2, but I just don't think I'm going to grasp this method anytime soon.
    Last edited by Cod; 02-20-2011 at 06:50 AM.

  9. #9
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    You need a second for loop inside the if block, not a couple of statements.

    The outer for loop takes you to the negative number, the inner one will walk along changing the array values.

    Java Code:
    j=0 
    
    a  b  c  -1  d  e  f
    
              * first loop stops here at i=3

    What happens if we swap d and j?

    Java Code:
    j=d  
    
    a  b  c  -1  0  e  f
    
                 *

    And then swap e and j?

    Java Code:
    j=e
    
    a  b  c  -1  0  d  f
    
                    *
    And finally swap f and j?

    Java Code:
    j=f
    
    a  b  c  -1  0  d  e
    
                       *

    In short we have to walk down the array swapping the array items with the value of j

    Java Code:
    int j = 0;
         
    for (int i = 0; i < a.length; i++) {
        if (a[i] < 0) {
            for(int i2 = ???; i2 < ???; i2++) {
                // swap the values of a[i2] and j
                // this may involve a second variable
            }
            break; // we've finished!
             
        }
    }

  10. #10
    Cod
    Cod is offline Member
    Join Date
    Nov 2009
    Location
    Honolulu, HI
    Posts
    59
    Rep Power
    0

    Default

    The concept I understand, its the implementation giving me an issue. I know exactly how to say it in plain language, but coding language is another story. I'll keep working at it and see where I can get.

    Thanks again for the guidance.

  11. #11
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    I would not do two loops. I would do one simple for loop, with an int lastVal variable initialized to 0 and a boolean negFound variable initialized to false -- both initializations outside the loop, of course. My thinking is that you have to do something at every position of the array -- either check if it's negative or shift it right. Storing the initial 0 is simply a special case of shifting right, and is easily handled with the lastVal variable initialized to 0. If you do it this way, you will need another int tmp variable within the loop.

    If you do go with two loops instead of one, you may find it easier to start the second loop from the end of the array, heading toward the index where you need to place the 0.

    -Gary-

  12. #12
    Cod
    Cod is offline Member
    Join Date
    Nov 2009
    Location
    Honolulu, HI
    Posts
    59
    Rep Power
    0

    Default

    I'm looking at my first try again and trying to figure out how to manipulate the loop to only add a zero after the first negative number...not all.

    I've been looking at pbrockway2's loop all morning and still drawing a blank.

  13. #13
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Quote Originally Posted by Cod View Post
    The goal is to find out if an array has a negative integer. If it does, the program is meant to place a 0 (zero) in the index right after the first negative number and shift subsequent elements to the right, dropping the last element. If there is no negative number, the program should return the original array.

    So, to answer your question, the code is trying to find and change.
    What happens if the negative number is the very last element in the array?

Similar Threads

  1. Find the second largest number in the array
    By radhi16 in forum New To Java
    Replies: 5
    Last Post: 01-13-2011, 06:08 PM
  2. Find max number in 2D array?
    By spatel14 in forum New To Java
    Replies: 3
    Last Post: 06-30-2010, 05:27 PM
  3. find the greatest and lowest number in 2D array
    By le_albina@hotmail.com in forum New To Java
    Replies: 2
    Last Post: 03-31-2009, 12:09 AM
  4. [SOLVED] Array of first negative number
    By random0munky in forum New To Java
    Replies: 9
    Last Post: 12-09-2008, 12:17 AM
  5. Replies: 8
    Last Post: 04-22-2008, 04:21 AM

Posting Permissions

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