CSCE 145: Algorithmic Design I
"abcde" "12345"then it should return a String with the value:
"a1b2c3d4e5"
/** * Interleaves the letters of first and second. Assumes that first and second have the same length. * @return the interleaved string */ public static String interleave(String first, String second){ String result = ""; for (int i =0; i < first.length(); i++){ result += first.substring(i, i+1) + second.substring(i,i+1); } return result; }
long
values representing phone numbers and prints
out how many of those phone numbers are in Columbia (803),
Greenville (864), and Charleston (843). You must use a switch
statement in your method.n
as input:
long[] n = {8031234567l, 8649878787l, 8031223456l, 8034543212l, 8642323214l, 8432341231l};you will print out:
Columbia:3 Greenville:2 Charleston:1
public static void countAreaCodes (long[] phoneNumber){ int columbia = 0; int greenville = 0; int charleston = 0; for (int i =0; i < phoneNumber.length;i++){ int areaCode = (int) (phoneNumber[i] / 10000000); switch (areaCode) { case 803: columbia++; break; //Don't forget the breaks! case 864: greenville++; break; case 843: charleston++; } } System.out.println("Columbia:" + columbia); System.out.println("Greenville:" + greenville); System.out.println("Charleston:" + charleston); }
public class Enigma { private static int x; protected String s; public Enigma(int x, String s){ System.out.println("Creating an Engima"); this.x = x; this.s = s; } public void addItUp(int z){ x = x + z; } public void merge(Enigma e){ s = s + "+" + e.s; } public String toString(){ return "s=" + s + " x=" + Integer.toString(x); } } public class Mystery extends Enigma { private int y; public Mystery (int x, int y, String s){ super(x,s); System.out.println("Creating a Mystery"); this.y = y; } public void addItUp(int z){ y = y + z; } public String toString(){ return super.toString() + " y=" + Integer.toString(y); } } public class Paradox extends Mystery { public Paradox(int x, int y, String s) { super(x, y, s); System.out.println("Creating a Paradox"); } public void merge (Paradox p){ s = "Do not cross the paradoxes!"; } } public class Main { public static void main(String[] args) { Paradox p = new Paradox (5,10,"This sentence is false"); Enigma e = new Enigma(33, "Black hole"); System.out.println(p); System.out.println(e); e.merge(p); System.out.println(e); p.merge(p); System.out.println(p); e.merge(p); System.out.println(e); p.addItUp(100); System.out.println(p); Enigma e2 = (Enigma)p; e2.addItUp(500); System.out.println(e2); } }
Creating an Engima Creating a Mystery Creating a Paradox Creating an Engima s=This sentence is false x=33 y=10 s=Black hole x=33 s=Black hole+This sentence is false x=33 s=Do not cross the paradoxes! x=33 y=10 s=Black hole+This sentence is false+Do not cross the paradoxes! x=33 s=Do not cross the paradoxes! x=33 y=110 s=Do not cross the paradoxes! x=33 y=610
1and this is a 4x4 diagonal matrix:
1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1Implement a method that takes an integer n and returns an n x n array of integers that is a diagonal matrix.
public static int[][] makeDiagonalMatrix (int size){ int [][] result = new int[size][size]; for (int i = 0; i<size; i++ ){ result[i][i] = 1; } return result; }
Tracker
which keeps track (in variables) of
toString() method has been called
toString()
invoked.public class Tracker { private static int totalCount = 0; private int count; public Tracker(){ count = 0; } public String toString() { count++; totalCount++; return ""; } }
Exception
called
SilentException
such that a we do not have
to place within a try.catch
block a method that
throws SilentException
.
public class SilentException extends RuntimeException { }
Order
, which has methods
(these exists, you don't have to write them):
boolean oversized()
: returns true if this order is for an oversized item.CARRIER getCarrier()
: where CARRIER is defined as enum CARRIER {UPS, FEDEX, USPS}
, returns the carrier. (A carrier is a company that ships packages. UPS, FEDEX, and USPS are the names of three different carrier companies.)boolean rush()
: return true if this a rush order.double
getShippingCosts(Order o)
and it will calculate the the
shipping and handling costs. The shipping costs for the different
carries are given in this table: UPS | FEDEX | USPS |
|
---|---|---|---|
Regular | $10 | $12 | $9 |
Oversized | $15 | $22 | $9 |
public static double getShippingCosts(Order o){ double basePrice = 0; switch (o.getCarrier()) { case UPS: if (o.oversized()) basePrice = 15; else basePrice = 10; break; case FEDEX: if (o.oversized()) basePrice = 22; else basePrice = 11; break; case USPS: basePrice = 9; } if (o.rush()) basePrice = basePrice * 1.10; basePrice += 4; return basePrice; }
String
input which represents a DNA sequence and
returns the index of the start of longest string of 'A' letters
in the sequence. If there are no A's then return -1. For example, /** * This solution is good enough for 145*/ public static int longestRepeatA(String dna){ int longestIndex = -1; int longestCount = 0; for (int i =0; i < dna.length(); i++){ int lengthA = 0; while (i + lengthA < dna.length() && dna.charAt(i+lengthA) == 'A'){ lengthA++; }; if (lengthA > longestCount){ longestCount = lengthA; longestIndex = i; } } return longestIndex; } /** More experienced developers realize that the above is O(N^2) and that * there is a way to implement it in linear time, like this: */ public static int longestRepeatB(String dna){ int longestIndex = -1; int longestCount = 0; int count = 0; for (int i = 0; i < dna.length(); i++){ if (dna.charAt(i) == 'A') { count++; } if (count > longestCount) { longestCount = count; longestIndex = i - count + 1; } if (dna.charAt(i) != 'A'){ count = 0; } } return longestIndex; }
double getAverageDropFourLowest(double [] grade)Assume that
grades.length >= 5
. For example, when given
double[] grade = {100,0,0,0,5,80,90};as input, your method should return
90.0Alert: Notice that this has to work when the lowest grades match, like in the example above where 3 of them where 0.
/** Returns an an array identical to grades but without the lowest number in grades dropped. * if there are more than one minimum we only drop the first one. * @param gradesthe array of grades * @return a new array of size 1 less than grades. */ public static double[] dropMin(double [] grade){ double minval = grade[0]; double[] result = new double[grade.length - 1]; for (double i : grade){ if (i < minval) minval = i; } int j = 0; //index into result for (int i = 0; i < grade.length; i++){ if (j < i){ //already dropped min, so just copy the rest of the array result[j++] = grade[i]; } else if (grade[i] > minval) { //not the min result[j++] = grade[i]; } //if j==i and grades[i] == minval we do nothing, so i increases while j stays the same, // thus ignoring this grade[i] } return result; } /** Returns the average after dropping the lowest 2 grades. */ public static double getAverageDropFourLowest(double [] grades){ double[] g = FinalTest.dropMin(grades); g = FinalTest.dropMin(g); g = FinalTest.dropMin(g); g = FinalTest.dropMin(g); double sum = 0; for (double i : g){ sum += i; } return sum / (double) g.length; }
public class MyExceptions { public int trySomething(int x) throws Exception{ if (x < 0) { throw new Exception("X is less than 0"); } return 5; } public static void main(String[] args){ MyExceptions m = new MyExceptions(); try { System.out.println("Starting"); int result = m.trySomething(10); System.out.println("Got " + result); result = m.trySomething(- 10); System.out.println("Got " + result); System.out.println("No more tries"); } catch (Exception e){ System.out.println(e.getMessage()); } System.out.println("Done"); } }
Starting Got 5 X is less than 0 Done
catch
block? Would the program
compile or not? If you think it would not compile then explain
what the compiler complains about. If you think is would compile
then show what the program would print out when run.
try
without a catch
.
Employee
,
with data members String name
and int
salary
. Make sure that instances of your
Employee
can be written out to a binary file. But,
do not write the code to write instances to a file, just
make sure that instances of Employee
can be written
out to a binary file.
public class Employee implements Serializable { private String name; private int salary; /** Add other methods, as needed. */ }
123432 3.14151 Ringowrite a program that reads those three values from the text file into an integer, double, and string variables, respectively.
import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class ReadFile { public static void main (String[] args){ String fileName = "data.txt"; try { Scanner inputStream = new Scanner(new File(fileName)); int i = inputStream.nextInt(); inputStream.nextLine(); double d = inputStream.nextDouble(); inputStream.nextLine(); String s = inputStream.next(); System.out.println("i=" + i + "\nd=" + d + "\ns=" + s); } catch (FileNotFoundException e){ System.out.println("File Not Found"); } } }
gcd
) of two numbers x and y is by using the following recursive definition of gcd(x,y)
:
the gcd(x,y) is equal to the gcd of y and x%y, the gcd(x,0) is equal to x.Implement a recursive function that calculates the greatest common division of any two integers.
public class GCD { /** Calculate the greatest common division, using the recursive function: gcd(x,y) = gcd(y,x%y) gcd(x,0) = x */ public static int gcd (int x, int y){ if (y == 0) return x; return GCD.gcd(y, x%y); } public static void main (String[] args){ System.out.println(GCD.gcd(10,5)); System.out.println(GCD.gcd(10,1)); System.out.println(GCD.gcd(8,6)); System.out.println(GCD.gcd(121,11)); } }
import java.util.ArrayList; public class Test<Type, E>{ private ArrayList<Type> list; private ArrayList<E> another; public Test(){ list = new ArrayList<E>(); another = new ArrayList<E>(); } public Type badFunction(E x, Type t){ E y = x; Type tt = t; list.add(t); another.add("Alice"); Test<String,String> justMe = new Test<String,String>(); justMe.add("Bob", "Charlie"); return tt; } }
list = new ArrayList<E>();is wrong because the type
E
should be Type
as per the declaration of list
.
another.add("Alice");because we cannot assume that the type of
another
will be ArrayList<String>
.
The Towers of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:
1. Only one disk may be moved at a time.
2. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
3. No disk may be placed on top of a smaller disk.
Below you will find a partial implementation of a Tower of Hanoi with two methods missing: getHeight and hanoi. For this test you will implement these methods.
--- the start Pole, destination Pole and the intermediate Pole are labeled A, B, C.
--- Each disk is labeled (from 1 to the n, n is the height of the tower)
--- Disk 1 is the smallest disk, and Disk n is the largest one.
Hint : The idea is that the method of moving n disks from start pole to destination pole is the same as the method of moving n-1 disks. For example, initially the tower has height 5, we must recursively move a tower of height 4 from A to C, move the biggest disk 5 from A to B (by simply calling method moveDisk), and finally recursively move the tower of height 4 to B from C.
public class HanoiTower { static int moves = 0; //number of moves so far /*Method getHeight is used to get the height of tower from user input*/ static int getHeight() { // TO DO } /*Method hanoi moves the tower of height n recursively * it accept four arguments: the height of the current tower n, the fromPole, the toPole and the withPole. * @param n the height of the current tower * @param fromPole the start pole * @param toPole the destination pole * @param withPole the intermediate pole * */ static void hanoi(int n, char fromPole, char toPole, char withPole) { // TO DO } /*Method moveDisk move the disk of diskLabel by simply printing on the console each move*/ static void moveDisk(int diskLabel, char fromPole, char toPole) { moves++; System.out.println("steps: "+ moves); System.out.println("Move " + diskLabel + " from " + fromPole + " to " +toPole); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int TowerHeight; char FromPole='A', ToPole='B', WithPole='C'; System.out.println("Please Enter Tower height..."); TowerHeight = getHeight(); hanoi(TowerHeight, FromPole, ToPole, WithPole); } }
Here is the output of height of 3 after you properly implement the methods:
Please Enter Tower height...
3
steps: 1
Move 1 from A to B
steps: 2
Move 2 from A to C
steps: 3
Move 1 from B to C
steps: 4
Move 3 from A to B
steps: 5
Move 1 from C to A
steps: 6
Move 2 from C to B
steps: 7
Move 1 from A to B
Notes:
Submit your HanoiTower.java file to espiggy@gmail.com before 4:00pm. No late submission accepted!