Homework Assignment 2

(Due to Wednesday July 14, 8:00am)

Question 1: (String)

An English word x is less than another English word y, if the position of x is before the position of y in an ordinary dictionary. For instance, "elephant" is less than "puma" because 'e' is less than 'p'. or "ephemer" is greater than "elephant" cause the first letter is the same while the second in "ephemer" is a 'p' which is greater than 'l'. This order can be generalized to any string which only contains letters, e.g. "cde" is less than "xyz".

Write a method to check if string x is less than string y.
Input: two string x and y which only contain letters a, b, ..., z are given as arguments to your method.
Output: print TRUE if x is less than y; otherwise print FALSE .

Your program could be written in the following format:

      class StringApplication {

          public static boolean less(String x, String y) {
            // your program here
          }

          public static void main(String args[]){

            // test several cases here 
	    System.out.println("elep < puma = "+less("elep, "puma"));
            System.out.println("xyz < cde = "+less("xyz", "cde"));
	  }

      }
    

Question 2: (String)

Write a method to check if all parentheses in the input string are matched.
Input: an arbitrary string str is given as argument to your method .
Output: print MATCH if all the parentheses in str are matched, otherwise print NO MATCH.

For example, if the input string str is "a(b))cde(fg)", then your program should print NO MATCH; if the input string is "a(()b)c", then your program should print MATCH.

Question 3: (Array)

Write a method which left circular shift an integer array n positions.
Input: an integer array a[] and a non-negative integer n are given as arguments to your method.
Output: an array which is the result of left circular shift the array a[] n position.

For example, if the input array is {1,2,3,4,5} and n = 3, then the result is {4,5,1,2,3}.

Your program could be written in the following format:

      class ArrayApplication {

          public static int[]  shift(int[] a, int n) {
            // your program here
          }

          public static void main(String args[]){

            int[] x = {1, 2, 3, 4, 5};
            x = shift(x, 3);

            // print all the integers in x
	  }
      }
     

Question 4: (Array)

Write a method which combines two sorted integer arrays into another sorted array.
Input: two sorted integer arrays a[] and b[].
Output: a sorted array which contains and only contains the all integers in a[] and b[].

For example, if a={12, 14, 25, 46} and b={7, 18, 23, 46}, then the result should be {7, 12, 14, 18, 23, 25, 46, 46}.