More With Arrays Solutions

From CompSciWiki
Revision as of 23:23, 5 December 2007 by Christopher (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > More With Arrays > Solutions


Introduction

This section contains all of the solutions to the review questions and exercises for More With Arrays chapter.

   

{{{Body}}}

Review Questions

Passing Arrays using Methods

  1. Add the square brackets
    int[] x 
  2. To get the length of an array of characters I would use: charVariable.length;
  3. To get the length of a String I would use: stringVariable.length();
  4. To get the length of an array of Strings I would use: sringArrayVariable.length;

Working with Paritally Filled Arrays

  1. Sometimes the default values have conflicts with input values.
  2. You can determine if all of the array indexes are full faster.

Arrays of Strings

Searching Arrays

  1. No, the array does not need to be sorted for a linear search, but it is more efficient if it is.
  2. Yes, the array does need to be sorted for a binary search.
  3. A binary search is more efficient.
  4. The binary search.

Sorting Arrays

Parallel Arrays

  1. Parallel arrays are no more tied together than two regular int and string variables are. the only thing tying them together is their common size and your use of them.
  2. No, you must make a customized sorting method that keeps all data in the arrays in parallel.

Exercises

Passing Arrays using Methods

Question:
Write a small method that accepts an array of characters, converts the characters into their ascii equivalent, then returns those values in an array of integers.

Solution:

public int[] ascii(char[] letters)
{
    int[] asciiLetters = new int[letters.length];
    for(int i = 0; i < letters.length]; i++)
        asciiLetters[i] = letters[i]; //Since a char variable is going into an int variable, it will auto convert.

    return asciiLetters;
}

Apply the binary search

Question:
Modify the binarySearch() algorithm to keep count of how many elements the algorithm checks to find the desired element. Print out each checked element's value (in other words, the value compared with the search value.)

Solution:
First, to keep count of the number of elements checked, we must at a variable, count. This variable will be incremented (count++) each time we do a comparsion (three times.)

Secondly, to print each element checked, we can simply add a System.out.println() statement at the end of our while loop. For esthetics only, we also print out the count variable.

public static int binarySearch(int[] list, int searchValue)
{
	int left;               //left element index
	int right;              //right element index
	int middle;             //middle element index
	int result;             //element that searchValue was found in
	int middleElement;      //middle value (comparing)

        int count;              //# element checked during search

	result = -1;            //return -1 if searchValue is not found
	left = 0;               //left index starts at the first element
	right = list.length-1;  //right index starts at the last element

        count = 0;              //we haven't checked any elements yet

	while ((left <= right) && (result == -1))
	{//left and right boundaries do not overlap and searchValue is not found

		middle = (left + right) / 2;
		middleElement = list(middle);

		if (middleElement == searchValue)
		{//we have found our searchValue
			result = middle;

                        count++;
		}

		else if (middleElement < searchValue)
		{//need to discard left portion of array
			left = middle + 1;

                        count++;
		}

		else if (middleElement > searchValue)
		{need to discard right portion of array
			right = middle – 1;

                        count++;
		}
 
                System.out.println("Value compared: " + middleElement);
                System.out.println("Number of elements counted: " + count);

	}//while
	return result;
}//binarySearch()

Working with partially filled arrays

Question:
Modify the binarySearch() algorithm to keep count of how many elements the algorithm checks to find the desired element. Print out each checked element's value (in other words, the value compared with the search value.)

Solution:
First, to keep count of the number of elements checked, we must at a variable, count. This variable will be incremented (count++) each time we do a comparsion (three times.)

Arrays of Strings

Solution:

public class PrintCities // We want an actual program here... This needs to run as-is!
{
  // Bonus points: Use of constants
  final String WPG = "Winnipeg";
  final String TOR = "Toronto";
  final String OTT = "Ottawa";
  final String EDM = "Edmonton";
  final String VAN = "Vancouver";

  // Bonus points: Use of a method
  public static void doThePrint()
  {
    String[] cities = new String[5];

    // We did assume that cities could be hard-coded!
    // Any cities could be used, really... YMMV

    cities[0] = WPG;
    cities[1] = TOR;
    cities[2] = OTT;
    cities[3] = EDM;
    cities[4] = VAN;

    // Bonus points: Use of a loop
    for( int i = 0; i < cities.length; i++ )
    {
      System.out.println( cities[i] );
    }// end for
  }// end doThePrint()

  public static void main( String[] args )
  {
    doThePrint(); // Bonus points (as above)
  }// end main
}// end PrintCities

Parallel Arrays

Question:
Write a program that uses a set of parallel arrays to store the name, age and addresses of 5 people you know (Just hard-code these). Have the program. Have the program do the following printouts separately: name and age, age and address and name and address.

Solution:

public static void main(String []args)
{
    //just examples of what your hard-coded parallel arrays should look like
    String []names = {"Joe","Greg","Phil","Alice","Danielle"};
    int []ages = {18,19,20,21,22};
    int []addresses = {"123 Fake Ave.","124 Fake Ave.","125 Fake Ave.","126 Fake Ave.","127 Fake Ave."};

    int i;
    System.out.println("Names and ages");
    for(i = 0; i < 5; i++)
    {
        System.out.println("Name: " + names[i] + " Age: " + ages[i]);
    }

    System.out.println("Ages and Addresses");
    for(i = 0; i < 5; i++)
    {
        System.out.println("Age: " + ages[i] + " Address: " + addresses[i]);
    }
     
    System.out.println("Names and Addresses");
    for(i = 0; i < 5; i++)
    {
        System.out.println("Name: " + names[i] + " Address: " + addresses[i]);
    }
    
}

After running the program, the output will look like this:

Names and Ages
Name: Joe Age: 18
Name: Greg Age: 19
Name: Phil Age: 20
Name: Alice Age: 21
Name: Danielle Age: 22
Ages and Addresses
Age: 18 Address: 123 Fake Ave.
Age: 19 Address: 124 Fake Ave.
Age: 20 Address: 125 Fake Ave.
Age: 21 Address: 126 Fake Ave.
Age: 22 Address: 127 Fake Ave.
Names and Addresses
Name: Joe Age: 18
Name: Greg Age: 19
Name: Phil Age: 20
Name: Alice Age: 21
Name: Danielle Age: 22