Sunday, 6 November 2016

Chapter 11 Exercise 10, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

11.10 (Implement MyStack using inheritance) In Listing 11.10, MyStack is implemented
using composition. Define a new stack class that extends ArrayList.
Draw the UML diagram for the classes and then implement MyStack. Write
a test program that prompts the user to enter five strings and displays them in
reverse order.

import java.util.ArrayList;

public class MyStack  extends ArrayList<Object> {


    public Object peek() {
        return get(size() - 1);
    }

    public Object pop() {
        Object o = get(size() - 1);
        remove(size() - 1);
        return o;
    }

    public void push(Object o) {
        add(o);
    }


    @Override /** Override the toString in the Object class */
    public String toString() {
        return "stack: " + super.toString();
    }
}

import java.util.Scanner;

public class Exercise_10 {

    public static void main(String[] args) {

        MyStack stack = new MyStack();
        Scanner input = new Scanner(System.in);
        System.out.print("Enter 5 strings... ");
        for (int i = 0; i < 5; i++) stack.push(input.next());

        System.out.println("Displaying them in reverse order.");
        while (stack.size() > 0) {
            System.out.println(stack.pop());
        }
    }
}

Chapter 11 Exercise 9, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

11.9 (Largest rows and columns) Write a program that randomly fills in 0s and 1s
into an n-by-n matrix, prints the matrix, and finds the rows and columns with the
most 1s. (Hint: Use two ArrayLists to store the row and column indices with
the most 1s.) Here is a sample run of the program:
Enter the array size n: 4
The random array is
0011
0011
1101
1010
The largest row index: 2
The largest column index: 2, 3
import javafx.scene.control.TextField;

public class Kit {

    public static final int NOT_VALID = -1;


    public static String randomNumbers(int size) {

        String s = "";
        for (int i = 0; i < size; i++) {
            s += " " + (int) (Math.random() * 100);
        }

        return s;
    }

    public static Object[] getArray(Object... objects) {
        Object[] temp = new TextField[objects.length];
        for (int i = 0; i < objects.length; i++) {
            temp[i] = objects[i];
        }
        return temp;
    }

    public static String binaryFormat(String binaryString) {


        StringBuilder string = new StringBuilder(binaryString);


        int extraZeros = string.length() % 4;

        if (extraZeros != 0) {
            for (int i = 0; i < extraZeros; i++) {
                string.insert(0, "0");
            }
        }

        for (int i = string.length() - 1; i >= 0; i--) {

            if (i % 4 == 0 && i != 0) {
                string.insert(i, " ");
            }
        }

        return string.toString();

    }
    public static String hexToBinary(String hex) {

        return decimalToBinary(hexToDecimal(hex));
    }

    public static String decimalToBinary(long n) {

        StringBuilder stringBuilder = new StringBuilder();
        while (n > 0) {

            stringBuilder.insert(0, n & 1);
            n >>= 1;
        }

        return stringBuilder.toString();
    }

    public static String decimalToHex(long n) {

        StringBuilder stringBuilder = new StringBuilder();
        while (n > 0) {

            stringBuilder.insert(0, decimalToHexChar(n % 16));
            n /= 16;

        }

        return stringBuilder.toString();
    }
    public static long hexToDecimal(String hex) {

        if (!isHexadecimal(hex)) return NOT_VALID;

        long n = 0;

        int placeValue = hex.length() - 1;
        for (int i = 0; i < hex.length(); i++) {

            char ch = hex.charAt(i);

            if (isNumeric(ch)) {
                n += (charToDecimal(ch) * Math.pow(16, placeValue--));
            } else {
                n += hexLetterToInt(ch) * Math.pow(16, placeValue--);

            }
        }
        return n;
    }

    private static int hexLetterToInt(char ch) {

        ch = Character.toUpperCase(ch);

        return (ch - 'A' + 10);
    }

    /** returns Z is n is > 15 */
    private static char decimalToHexChar(long n) {

        if (n > 15) return 'Z';
        if (n > 9) return (char)(n % 10 + 'A');


        return (char)(n + '0');
    }
    public static long stringToDecimal(String s) {

        long n = 0;
        int placeValue =  s.length() - 1;

        for (int i = 0; i < s.length(); i++) {

            int valid = charToDecimal(s.charAt(i));

            if (valid == NOT_VALID) return NOT_VALID;

            n += (Math.pow(10, placeValue--) * valid);

        }

        return n;
    }

    public static String decimalToString(long n) {

        StringBuilder s = new StringBuilder();

        while (n != 0) {

            s.insert(0, n % 10);
            n /= 10;
        }

        return s.toString();
    }

    public static int charToDecimal(char ch) {

        if (!isNumeric(ch)) return NOT_VALID;

        return ch - '0';

    }
    public static boolean isNumeric(String s) {

        for (int i = 0; i < s.length(); i++) {

            if (!isNumeric(s.charAt(i))) return false;
        }

        return true;
    }
    public static boolean isNumeric(char ch) {

        return (ch >= '0' && ch <= '9');
    }

    public static boolean isHexadecimal(String s) {

        for (int i = 0; i < s.length(); i++) {

            if (!isHexValid(s.charAt(i))) return false;
        }

        return true;
    }

    public static boolean isHexValid(char ch) {

        ch = Character.toUpperCase(ch);

        return isCharAtRange(ch, '0', '9') || isCharAtRange(ch, 'A', 'F');

    }


    public static boolean isCharAtRange(char ch, char start, char end) {

        return !(ch < start || ch > end);

    }

    public static int count(String str, char a) {

        int count = 0;
        for (int i = 0; i < str.length(); i++) {

            if (str.charAt(i) == a) count++;
        }

        return count;
    }

    public static void displayGrid(int[][] grid) {

        for (int[] aGrid : grid) {

            System.out.printf("%20s", "");
            for (int k = 0; k < aGrid.length; k++) {
                System.out.printf("|%-2d|", aGrid[k]);
            }
            System.out.println("");
        }

    }

    public static void displayGrid(int[] grid) {
        for (int i = 0; i < grid.length; i++) {

            System.out.printf("%-4d ", grid[i]);
            if ((i + 1) % 10 == 0)
            System.out.println("");
        }

    }

    public static void displayTimesTable(int x, int y) {
        // display 8x8 numbered grid to help solve exercise
        for (int i = 1; i <= y; i++) {

            System.out.printf("%20s", "");
            for (int k = 1; k <= x; k++) {
                System.out.printf("|%-2d|", i * k);
            }
            System.out.println("");
        }
    }

    public static int[] makeUnsortedArray(int size, int range) {
        int[] array = new int[size];

        for (int i = 0; i < array.length; i++) {
            array[i] = (int) (Math.random() * range + 1);
        }

        return array;
    }

    public static double[][] makeUnsortedArray(int rows, int columns, int range) {
        double[][] array = new double[rows][columns];

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array[i].length; j++) {
                array[i][j] = (int) (Math.random() * range + 1);
            }
        }

        return array;
    }


    public static int[] merge(int[] list1, int[] list2) {

        int[] merge = new int[list1.length + list2.length];
        int m = 0, l1 = 0, l2 = 0;
        boolean l1isFinished = false;
        boolean l2isFinished = false;

        while (!l1isFinished || !l2isFinished) {

            if (l1 == list1.length) l1isFinished = true;
            if (l2 == list2.length) l2isFinished = true;
            if (l1isFinished && l2isFinished) break;

            if (!l1isFinished && l2isFinished) merge[m++] = list1[l1++];
            else if (!l2isFinished && l1isFinished) merge[m++] = list2[l2++];
            else if (list1[l1] <= list2[l2]) merge[m++] = list1[l1++];
            else if (list2[l2] <= list1[l1]) merge[m++] = list2[l2++];

        }
        return merge;
    }

    public static boolean isSorted(int[] numbers) {

        for (int i = 0; i < numbers.length - 1; i++) {

            if (numbers[i] > numbers[i + 1]) return false;

        }
        return true;
    }

    public static void displayMatrix(double[][] matrix) {
        for (double[] aMatrix : matrix) {

            for (int column = 0; column < aMatrix.length; column++) {
                System.out.printf("%5.0f ", aMatrix[column]);
            }
            System.out.printf("\n");
        }
    }

    public static void display(Object[] objects) {

        int count = 1;
        for (Object o : objects) {
            System.out.printf("%4s\n", o.toString());
            if (count % 10 == 0) {
                System.out.println("");
            }
            count++;
        }
    }
}

import java.util.ArrayList;
import java.util.Scanner;
public class Exercise_09 {

    public static void main(String[] args) {

        System.out.print("Enter the array size n: ");
        int n = new Scanner(System.in).nextInt();
        int[][] m = new int[n][n];

        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[i].length; j++) {
                m[i][j] = (int) (Math.random() * 2);
            }
        }


        ArrayList<Integer> row = new ArrayList<>();
        ArrayList<Integer> column = new ArrayList<>();
        getHighestRow(m, row);
        getHighestColumn(m, column);

        Kit.displayGrid(m);
        System.out.println("Highest row: " + row);
        System.out.println("Highest column: " + column);

    }

    public static void getHighestRow(int[][] m, ArrayList<Integer> row) {

        int highest = 0;
        for (int i = 0; i < m.length; i++) {
            int occurrence = 0;
            for (int j = 0; j < m[i].length; j++) {

                if (m[i][j] == 1) {
                    occurrence++;
                }
            }
            if (highest < occurrence) {
                highest = occurrence;
                row.clear();
                row.add(i);
            } else if (highest == occurrence) {
                row.add(i);
            }
        }

    }
    public static void getHighestColumn(int[][] m, ArrayList<Integer> column) {

        int highest = 0;
        for (int j = 0; j < m[0].length; j++) {
            int occurrence = 0;
            for (int i = 0; i < m.length; i++) {

                if (m[i][j] == 1) {
                    occurrence++;
                }
            }
            if (highest < occurrence) {
                highest = occurrence;
                column.clear();
                column.add(j);
            } else if (highest == occurrence) {
                column.add(j);
            }
        }
    }
}

Chapter 11 Exercise 8, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

11.8 (New Account class) An Account class was specified in Programming
Write a test program that creates an Account with annual interest rate 1.5%,
balance 1000, id 1122, and name George. Deposit $30, $40, and $50 to the
account and withdraw $5, $4, and $2 from the account. Print an account summary
that shows account holder name, interest rate, balance, and all transactions.
Programming Exercises 447

import java.util.ArrayList;
import java.util.Date;

public class Account {

    protected String mName;
    protected int mId;
    protected double mBalance;
    protected double mAnnualInterestRate; // AnnualInterestRate is percentage.
    protected Date mDateCreated;
    protected ArrayList<Transaction> mTransactions;


    public Account() {
        mDateCreated = new Date();
        mTransactions = new ArrayList<>();
    }

    public Account(int id, double balance) {
        this();
        mId = id;
        mBalance = balance;
    }

    public Account(String name, int id, double balance) {
        this(id, balance);
        mName = name;

    }

    public int getId() {
        return mId;
    }

    public void setId(int id) {
        mId = id;
    }

    public double getBalance() {
        return mBalance;
    }

    public void setBalance(double balance) {
        mBalance = balance;
    }

    public double getAnnualInterestRate() {
        return mAnnualInterestRate;
    }

    public void setAnnualInterestRate(double annualInterestRate) {
        mAnnualInterestRate = annualInterestRate;
    }

    public Date getDateCreated() {
        return mDateCreated;
    }

    public double getMonthlyInterestRate() {
        return mBalance * (mAnnualInterestRate / 12) / 100;
    }

    public void withdraw(double amount) {
        mTransactions.add(new Transaction('W', amount, mBalance, "withdraw"));
        mBalance -= amount;
    }

    public void deposit(double amount) {
        mTransactions.add(new Transaction('D', amount, mBalance, "deposit"));
        mBalance += amount;
    }

    @Override
    public String toString() {
        return "Account name: " + mName + "\n" + "Interest rate: " + mAnnualInterestRate + "\n" + mTransactions;
    }

    public ArrayList<Transaction> getTransactions() {
        return new ArrayList<>(mTransactions);
    }

}

public class Exercise_08 {

    public static void main(String[] args) {

        Account account = new Account("George", 1122, 1000);
        account.setAnnualInterestRate(1.5);
        account.deposit(30);
        account.deposit(40);
        account.deposit(50);
        account.withdraw(5);
        account.withdraw(4);
        account.withdraw(2);
        System.out.println(account);
    }
}

Chapter 11 Exercise 7, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

11.7  (Shuffle ArrayList)
Write the following method that shuffles the elements in an ArrayList of integers.
public static void shuffle(ArrayList<Integer> list)



import java.util.ArrayList;

public class Exercise_07 {

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            list.add(i);
        }

        System.out.println(list);

        System.out.println("Shuffling list...");
        shuffle(list);
        System.out.println(list);
    }

    public static void shuffle(ArrayList<Integer> list) {

        // simple solution
        //Collections.shuffle(list);

        // manual shuffle
        for (int i = 0; i < list.size(); i++) {
            int randomIndex = (int) (Math.random() * list.size());
            int temp = list.get(randomIndex);
            list.set(randomIndex, list.get(i));
            list.set(i, temp);
        }

    }


}