Programming and Computer Science in Java:
Quiz #5a:   Methods, Doubles, Math Methods, Strings, Randoms
    David Kosbie, 2002-2003
See Course Home Page

Quiz Date:  Tue, Mar 25, 2003

Question 1:  Palindrome.  Write a Java program which repeatedly reads in a word, quitting when the user enters "done", and prints out whether or not that word is a palindrome.  That is, whether it is the same backwards as forwards.  Some palindromes:  "mom", "dad", "madam", "detartrated", as well as nonsensical words such as "foof", "abccba", and so forth.  Note that your program must use a method with the following signature:
     public static boolean isPalindrome(String s)

Question 2:  Hamming Distances.  Read in an integer N followed by a word W followed by N more words of the same length as W.  Output the word after W which is "closest" by Hamming Distance to W -- that is, the one which differs by the fewest characters from W.
Sample Input:  4 port pond tart post cork 
Sample Output:  post
Note that your program must use a method, hammingDistance, which takes two Strings as arguments and returns an integer, the hammingDistance between the strings.

Question 3:  Approximating the Natural Log of 2.  The natural logarithm of 2 is written ln(2), and can be computed as follows:
     ln(2) = 1/1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + …
Write a Java program which uses this technique to compute the ln(2), stopping when the next term to be added or subtracted is smaller than 0.00001.  Note that you may not use the Math.log method in this answer.

Question 4:  Random Doubles in a Range.  Write a Java program which reads in two doubles, lo and hi, and prints out 100 random doubles in the range [lo,hi] (ie, inclusive).  Your program must use a method, random, which takes a lo and hi and returns a value in that range.  

Question 5:  Random Integers in a Range.  Write a Java program which reads in two integers, lo and hi, and prints out 100 random integers in the range [lo,hi] (ie, inclusive).  Your program must use a method, random, which takes a lo and hi and returns a value in that range.  

Question 6:  Duplicate Rolls.  Write a Java program which determines the probability (output as a percentage) of rolling two six-sided dice twice and coming up with the same sum on both rolls.  So, rolling 2,3 and then 1,4 would be a success, as they both sum to 5.  Your program should take the number of trials (ie, experiments) to run as the sole input.  Your program must use a method, rollDice, which returns the sum of rolling two six-sided dice.  That method, in turn, must use a method, rollDie, which returns the result of rolling one six-sided die.

Good luck.

DK


See Course Home Page