Monday, October 8, 2012

Hints on Array Problems

Many of you are struggling on the array problems. In this post, I have provided some hints on some of the solutions. In some cases, I provide you with an algorithm to help you find a solution. For some others, I give you pieces of code.

 First, here is how you parse an array of unknown length. Lets say you have an array called a. Here is a loop that prints every element, one per line:

          for (int i=0; i < a.length; ++i)
         { 
               System.out.println(a[i]);
         }


Notice we use the length attribute of array a to figure out how many times we need to run through the loop. That means this loop will work for any length array.

Ok, now for some help on individual problems:

7.4: create an integer called previousValue and set it initially to be equal to the first element of the array. Then set up a loop to parse the array from the second element to the last element. If the current element being checked is smaller than the previousValue immediately return false. Otherwise, update previousValue to the current element and go to the next element in the loop. If you make it through the entire loop without getting to the return false statement, just return true.

7.11: Its important to understand that the printBackwards() method does not return a value. It justs prints some stuff. The trick here is to parse the array from the largest index to the smallest. So use a loop like this:

          for (int i=a.length-1; i >=0; --i)    // i is the index of the next element from biggest to zero
         { 
               // add print statements here
         }

7.1:  Create an integer called returnValue and set it equal to -1. Parse the array from start to finish. If the target is located, update the returnValue to the current index. If the target is in the array multiple times, the returnValue will simply get updated multiple times. After parsing the entire array, just return returnValue;

7.2:  Parse the array and locate the largest element. Parse the array and locate the smallest element. subtract the two answers and add one. Return that as the final answer.

7.3: Create an integer called returnValue and initialize it to zero. Parse the array. For each element, check to see if it is greater than equal to the minimum value AND less than or equal to the max value. If so, increment the returnValue. After parsing the entire array, return the returnValue.

No comments:

Post a Comment