CPE 103 Homework Solutions


Homework #1

#1.  C
#2.  A
#3.  B 

#2.3
An array has its size associated with it. An ArrayList has a capacity in addition to size. Adding an
element to an ArrayList will automatically expand the capacity of the array if needed.

#2.9
import java.io.*;
import java.util.*;

public class Checksum
{
    public static void main(String[] args) throws IOException
    {
        int checksum = 0;
        Scanner fileScanner = null;
        fileScanner = new Scanner(new File(args[0]));
        while (fileScanner.hasNextLine())
        {
            String line = fileScanner.nextLine();
            for (int i = 0; i < line.length(); i++)
            {
                checksum += line.charAt(i);
            }
        }
        System.out.println("File checksum = " + checksum);
    }
}


#2.15


    public static double sum(double[][] arr)
    {
        double sum = 0.0d;
        for (int row = 0; row < arr.length; row++)
        {
            for (int col = 0; col < arr[row].length; col++)
            {
                sum += arr[row][col];
            }
        }
        return sum;
    }

    public static double average(double[][] arr)
    {
        double sum = 0.0d;
        int row = 0, col = 0;
        for (row = 0; row < arr.length; row++)
        {
            for (col = 0; col < arr[row].length; col++)
            {
                sum += arr[row][col];
            }
        }
        return sum / (row * col);
    }

    public static double mode(double[][] arr)
    {
        double[] newArr = new double[arr.length * arr[0].length];
        int counter = 0;
        for (int row = 0; row < arr.length; row++)
        {
            for (int col = 0; col < arr[row].length; col++)
            {
                newArr[counter++] = arr[row][col];
            }
        }
        java.util.Arrays.sort(newArr);
        int modeCounter = 1;
        int maxMode = 1;
        double modeValue = newArr[0];
        for (int i = 0; i < newArr.length - 1; i++)
        {
            if (newArr[i] == newArr[i + 1])
            {
                modeCounter++;
            }
            if (modeCounter > maxMode)
            {
                maxMode = modeCounter;
                modeValue = newArr[i + 1];
                modeCounter = 1;
            }
        }
        return modeValue;
    }




Homework #2

3.1
Encapsulation is the grouping together of data and the operations that apply to them to form an aggregate. Encapsulation is achieved in Java through the use of the class.
Information hiding makes implementation details, including components of an object, inaccessible. Information hiding is achieved in Java through the use of access modifiers.

3.10
An instance field is associated with a particular instance (or object) of a class. A static field is associated with the class itself and can be accessed from any instance of the class.

3.13
(a) Line 17 is illegal because p is a non‐static field and therefore needs an object reference in order to be reference in the main method (which is a static method). Line 18 is legal as q is created within the main method. (b) Line 20 and 23 are legal as NO_ SSN is a public static field that can be accessed via an object reference or a class name. Line 22 is legal because by default, name is visible. Line 21 and 24 are illegal because SSN is private. Also, Person.SSN is illegal as SSN is nonstatic.


3.18
public class Combolock
{
    private int num1;
    private int num2;
    private int num3;
    public Combolock ( int a, int b, int c)
    {
        num1 = a;
        num2 = b;
        num3 = c;
    }
    //returns true if the proper combination is given
    public boolean open ( int a, int b, int c)
    {
        return ( ( a == num1 ) && ( b == num2 ) && (c == num3 ) );
    }
    public boolean changeCombo( int a, int b, int c, int newA,
                                int newB, int newC )
    {
        if ( open( a, b, c) )
        {
            num1 = newA;
            num2 = newB;
            num3 = newC;
            return true;
        }
        return false;
    }

3.25
public static void printArray(int [][] arr)
{
    for (int row = 0; row < arr.length; row++)
    {
        for (int col = 0; col < arr[row].length; col++)
            System.out.print(String.format("%5d", arr[row][col]));
        System.out.println();
    }
}


3.28
public class BinaryArray
{
    private boolean [] arr = null;
    public BinaryArray(String init)
    {
        arr = new boolean[init.length()];
        for (boolean value : arr)
            value = false;
        for (int ch = 0; ch < init.length(); ch++)
        {
            boolean val = false;
            if (init.charAt(ch) == 'T')
                val = true;
            arr[ch] = val;
        }
    }
    public int size()
    {
        return arr.length;
    }
    public String toString()
    {
        String result = "";
        for (int i = 0; i < arr.length; i++)
            result += arr[i] + " ";
        return result;
    }
    public boolean get(int location)
    {
        return arr[location];
    }

    public void set(int location, boolean value)
    {
        arr[location] = value;
    }
}

4.6
(a) Only b.bPublic and d.dPublic are legal. (b) if main is in Base , then only d.dPrivate is illegal. (c) If main is in Derived, then b.bPrivate is illegal. (d) Assuming Tester is in the same package, then b.bProtect is visible in all cases. (e) place the statements below in the public section of their respective classes; (f) and (g) bPrivate is the only member not accessible in Derived.
Base( int pub, int pri, int pro )
{
    bPublic = pub; bPrivate = pri; bProtect = pro;
}
 
Derived( int bpub, int bpri, int bpro, int dpub, int dpri )
{
    super( bpub, bpri, bpro );
    dPublic = dpub; dPrivate = dpri;
}

4.7
Final classes may not be subclassed (by the use of inheritance). Non‐final classes can be subclassed. Final classes are generally used to provide an implementation of a class that should not be changed.

4.9
An interface is a class that contains a protocol but no implementation. As such it consists exclusively of public abstract methods and public static final fields. This is different from abstract classes, which may have partial implementations.

4.36
class Person implements Comparable
{
    public int compareTo(Object rhs)
    {
        Person p2 = (Person) rhs;
        return (name.compareTo(p2.name));
    }
}




Homework #3

5.4 All except x belong to the same group.

5.5 (a) Program A’s guarantee is ten times better than B’s.
(b) Program B’s guarantee is ten times better than A’s.
(c) the stated properties do not tell us anything about the average‐case performance.
(d) It is possible that program B will run faster on all inputs; the guarantee for B may be too pessimistic.

5.7 The total cost is  Ο(N*N)

5.8 The total cost is  Ο( N log N ) .

5.10  (a) O( N ); (b) O( N*N); (c) O( N*N).

5.14 About (a) 2.5 milliseconds (5 times longer);
(b) 3.5 milliseconds (500 * log(500) / 100 * log(100) = 5*log(500)/log(100), or about 7 times longer );
(c) 12.5 milliseconds ((500/100)2 or 25 times longer);
(d) 62.5 milliseconds ((500/100)3 or 125 times longer).

5.15 In this problem, we are given 120,000 times as much time.
a. For a linear‐time algorithm, we can solve a problem 120,000 times as large, or 12,000,000 (assuming sufficient resources);
b. For an Nlog N algorithm it is a little less (about 4,000,000 or so);
c. For a quadratic algorithm, we can solve a problem  sqrt(120000) = 346 times as large, so we can solve a problem of size 34,600;
d. For a cubic algorithm, we can solve a problem  cuberoot(120000) = 49 times as large, so we can solve an instance of size 4,900.

5.19
(Partial solution)
2 / N,   37,   sqrt(N),  N,   N log N,   N1.5 ,   N2 log N,   N3,   2N


5.20
Fragment 1: The running time is O( N ).
Fragment 2: The running time is O( N ).
Fragment 3: The running time is O( N2 ) because of two nested loops of size N each.
Fragment 4: The loops are consecutive, so the running time is O( N ).
Fragment 5: The inner loop is of size N*N so the running time is O( N3 ).
Fragment 6: The running time is O( N2 ).
Fragment 7: Here we have three nested loops of size N, N2, and N2, respectively, so the total running time is O( N5 ).
Fragment 8: The running time is O(log N).

5.23  Joe’s career path, at worst, is through companies whose employee size is 1, 2, 3... up to N. Thus, at most he could have worked for N companies. 

5.28 
a. N2
b. A 100-by-100 matrix has an N of 100. A 400-by-400 matrix has an N of 400. 400 is four times as large as 100. The running time is quadratic, so 4 * 42 seconds = 64 seconds.
(Alternately, you could reason more directly that the 400-by-400 matrix is 16 times larger, so 4 seconds times 16 = 64 seconds).



Homework #4 Solution

1. a.  O(N)       b. 3 seconds

2.  a.
    /**
     * Returns true if odd integer n is prime.
     * Worst-case running time is O(sqrt(n))
     */
     public static boolean isPrime( long n )
     {
         for( int i = 3; i * i <= n; i += 2 )
         {
             if( n % i == 0 )
             {
                 return false; // not prime
             }
         }
 
         return true;          // prime
     }



Homework #4.5 Solution
/**
 * Enum for a baseball player position
 * 
 */
public enum Player
{
     Pitcher, Catcher, Firstbase, Secondbase, Shortstop, Thirdbase, Leftfield, Centerfield, Rightfield;
     
}

import java.util.*;
/**
 * PlayerClient is a driver for the Player enum.
 */
public final class PlayerClient
{
    public static void main(String[] args)
    {
        // show all the players, in order. 
        for (Player p: Player.values())
        {
            System.out.println(p);
        }
        //Read a string from the user that represents a player, and creates an enum value.
        Scanner console = new Scanner(System.in);
        String input = console.nextLine();
        try 
        {
            Player player = Player.valueOf(input);
            // If the enum value is a Pitcher, print "Strike", otherwise print "Ball".
            if (player.equals(Player.Pitcher))
            {
                System.out.println("Strike");
            }
            else
            {
                System.out.println("Ball");
            }
        }
        catch (IllegalArgumentException ex)
        {
            System.out.println("Input is not a player.");
        }
    }
}

Homework #5 Solution

Problem 1 Solution
a) Only the Private fields can not be accessed.
b) Only g.gPrivate is illegal.
c) Only a.aPrivate is illegal.
d) The same as previous, only a.aPrivate is illegal.
e) Access to Gala is illegal. Only the Public fields can be accessed.
f) Only aLimited is illegal.
g) Place the statements below in the public section of their respective classes;
h) aPrivate is the only member not accessible in Gala.

Apple( int pub, int pri, int pro, int lim )
{
    aPublic = pub; aPrivate = pri; aProtect = pro; aLimited = lim
}

Gala( int apub, int apri, int apro, int gpub, int gpri )
{
    super( apub, apri, apro );
    gPublic = gpub; gPrivate = gpri;
}


Homework #6 Solution

  1. An integer can be assigned a value other than 1 to 9.  Use an enum instead.
  2. Checkerboards are two-dimensional, so use a 2-d array.
  3. Never represent monetary values with floating point data types.  Use int, BigDecimal, or a Money ADT.
  4. Arraylist allows items to be inserted in the middle, the queue of cars doesn't.  Use a Queue ADT.
  5. Song durations are never negative.  Use a Natural ADT or unsigned integer ADT.
  6. Strings can't do arithmetic calculations, which are common with dates.  Use a java Date.


Homework #7 Solution

6.2 (a)
public static int count( Collection<Collection<String>> c, String str )
{
    int count = 0;
    // go through each String object
    // in each Collection object in Collection c
    for( Collection strC : c )
    {
        for( Object o : strC )
        {
            String s = (String) o;
            if ( s.equals( str ) )
            {
                count++;
            }
        }
    }
    return count;
}
(b). O ( N2 )
(c). 18 milliseconds

6.10 
a. O(N)
b. O ( N2 )

c. 50k/10k = 5.
   4 * (5*5) = 100 seconds.

d. Use an enhanced for loop (for-each), for the lhs list,
   and use a manual interator for the rhs list.
        Iterator<Integer> iter = rhs.iterator();
        for( Integer num : lhs)
            if( !num.equals( iter.next() ) )
                 return false;
     
  
6.16
a. because size() changes each time through the loop.

b. remove at front is O(N) for array list, thus: O(N*N)
 
c. remove at front is O(1) for linked list, thus: O(N).


Homework #8 Solution

17.6 Copy the value of the next node in the current node and then delete the next node.
17.7 (a) Add a new node after position p and copy the element in position p to the new node. Then,
                        change data of position p to the new item.
        (b) Copy the next element to position p and delete the next node.



Homework #9 Solution


6.1
(a) The removed items are 6 and then 1.
(b) the removed items are 4 and then 8.

6.6
A double‐ended queue is easily implemented in constant time by extending the basic queue operations.

6.19
No solution provided; compile it and run it to determine the solution.

4)
Head
bird
mouse
fox

5)

bird
cat
dog

6)   4

7)  
4
5
8
 
9
8


72

7
72


65


11.1 Check yourself: download the author's code and run program.  (Note: weiss.utils.stack can be replaced with java.utils.stack).

9)
(a) xyz*+

(b) xy+z*

(c) xy-zab+*-
(This is the only correct answer if you followed the algorithm).



Homework 14


a.
 0
 1 105
 2 639  
 3 718 
 4 692
 5 538
 6 799
 7 254
 8 277
 9 512
10 101 
11 375
12 822
b.
 0 277
 1
 2 639
 3 718
 4 692
 5 538
 6 800
 7 254
 8 255
 9 100
10 101
11 375
12


Homework 15
1. 6

2. D

3. Yes.

4. Yes.

5.
	 public static long sumOfDigits(long x)
	 {
		  if (x < 10)
		  {
			   return x;
		  }	   
		  return (x % 10) + sumOfDigits( x / 10 );
	 }




Homework 16
18.1
(a) The root is A;
(b) Leaves are G, H, I, L, M, and K;
(c) The depth is 4;
(d)
    preorder:     A, B, D, G, H, E, I, J, L, M, C, F, K;
    postorder:    G, H, D, I, L, M, J, E, B, K, F, C, A;
    inorder:        G, D, H, B, I, E, L, J, M, A, C, F, K;
    level order: A, B, C, D, E, F, G, H, I, J, K, L, M.

18.2
Problem 18.2 Solution

Parent
Children
Siblings
Height
Depth
Size
A

B,C

4
0
13
B
A
D,E
C
3
1
9
C
A
F
B
2
1
3
D
B
G,H
E
1
2
3
E
B
I,J
D
2
2
5
F
C
K

1
2
2
G
D

H
0
3
1
H
D

G
0
3
1
I
E

J
0
3
1
J
E
L,M
I
1
3
3
K
F


0
3
1
L
J

M
0
4
1
M
J

L
0
4
1



18.3
a b b d d d b a c e e e c c a  (with newlines instead of blanks).


Part 2

The prefix, infix, and postfix expressions corresponding to this tree are:
prefix:    - * * a b + c d e
infix:      ( ( a * b ) * ( c + d ) ) - e
postfix:  a b * c d + * e -





Homework 21
Problem 1



A  B -> D

B  A -> C

C  B -> D -> G

D  A -> C -> E -> F

E  D -> F

F  D -> E

G  C



Problem 2

  A B C D E F G
A   1   1
B 1   1
C   1   1     1
D 1   1   1 1
E       1   1
F       1 1
G     1

Problem 3

  1 2 3 4 5 6 7
1   1 1 1
2       1 1
3           1
4     1     1 1
5       1     1
6
7           1
 



Homework 22
1.  Breadth-first
A  B I C H D G E F
B A C H I D G E F
E  D C F B G A H I
F  D G C E H B I A

2. Depth first A B C D E F G H I H B A I C D E F G G F D C B A I H E


Homework 23
Solved Graph
(There's one minor mistake in the solution that doesn't effect the final result, can you spot it?)