Download Chapter 6 Programming Exercise Solutions P6.1 public class

Document related concepts
no text concepts found
Transcript
Chapter 6 Programming Exercise Solutions
P6.1
public class ArrayPrinter
{
public static void main(String[] args)
{
int[] data = new int[10];
for (int i = 0; i < 10; i++)
{
data[i] = (int) (Math.random() * 100 + 1);
}
// Print out even indices
for (int i = 0; i < data.length; i = i + 2)
{
System.out.print(data[i] + " ");
}
System.out.println();
// Print out even elements
for (int i = 0; i < data.length; i++)
{
if (data[i] % 2 == 0)
{
System.out.print(data[i] + " ");
}
}
System.out.println();
// Print out elements in reverse order
for (int i = data.length - 1; i >= 0; i--)
{
System.out.print(data[i] + " ");
}
System.out.println();
// Print out only first and last element
System.out.printf("%d %d\n", data[0], data[data.length - 1]);
}
}
P6.2
Array methods that do the following:
a) Swap first and last elements in an array.
public static void swapFirstLast(int[] arr)
{
int last = arr.length - 1;
int temp = arr[0];
© John Wiley & Sons, Inc. All rights reserved.
1
arr[0] = arr[last];
arr[last] = temp;
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < 10; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " ");
}
System.out.println();
// Perform the swap.
swapFirstLast(randoms);
// Print again to see new order.
for (int i = 0; i < 10; i++)
{
System.out.print(randoms[i] + " ");
}
System.out.println();
}
b) Shift all elements by one to the right.
public static void rotateRight(int[] arr)
{
int last = arr.length - 1;
int temp = arr[last];
for (int i = last; i > 0; i--)
{
arr[i] = arr[i - 1];
}
arr[0] = temp;
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < 10; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " ");
}
System.out.println();
// Rotate the array once to the right.
rotateRight(randoms);
© John Wiley & Sons, Inc. All rights reserved.
2
// Print again to see new order.
for (int i = 0; i < 10; i++)
{
System.out.println(randoms[i] +
}
System.out.println();
" " );
}
c) Replace all even elements with 0.
public static void replaceEven(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) // Number is even
{
arr[i] = 0;
}
}
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < 10; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " ");
}
System.out.println();
// Replace the even elements.
replaceEven(randoms);
// Print again to see new elements.
for (int i = 0; i < 10; i++)
{
System.out.print(randoms[i] + " ");
}
System.out.println();
}
d) Replace each element except first and last by the larger of its two neighbors.
public static void replaceWithLargestNeighbor(int[] arr)
{
// Start loop at one, and stop before the end
for (int i = 1; i < arr.length - 1; i++)
{
if (arr[i - 1] > arr[i + 1])
{
arr[i] = arr[i - 1];
© John Wiley & Sons, Inc. All rights reserved.
3
}
else
{
arr[i] = arr[i + 1];
}
}
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < 10; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " ");
}
System.out.println();
// Replace with largest neighbor
replaceWithLargestNeighbor(randoms);
// Print again to see new elements.
for (int i = 0; i < 10; i++)
{
System.out.print(randoms[i] + " ");
}
System.out.println();
}
e) Remove the middle element if the array length is odd, or middle two if even.
public static void removeMiddle(int[] arr)
{
int size = arr.length;
if (size % 2 == 0) // Size is even
{
// Figure out starting point for removal
int firstToRemove = size / 2 - 1;
// Remove middle two elements
for (int i = firstToRemove; i < size - 2; i++)
{
arr[i] = arr[i + 2];
}
}
else
{
// Size is odd
// Figure out starting point for removal
int firstToRemove = size / 2;
// Remove middle element
for (int i = firstToRemove; i < size - 1; i++)
{
arr[i] = arr[i + 1];
© John Wiley & Sons, Inc. All rights reserved.
4
}
}
}
public static void main(String[] args)
{
int[] randoms = new int[11];
// Create a test array containing random numbers
for (int i = 0; i < randoms.length; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " " );
}
System.out.println();
// Remove the middle element(s)
removeMiddle(randoms);
// Print again to see new order.
for (int i = 0; i < randoms.length; i++)
{
System.out.print(randoms[i] + " ");
}
System.out.println();
randoms = new int[10];
// Create a test array with an even number of elements
for (int i = 0; i < randoms.length; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " " );
}
System.out.println();
// Remove the middle element(s)
removeMiddle(randoms);
// Print again to see new order.
for (int i = 0; i < randoms.length; i++)
{
System.out.print(randoms[i] + " ");
}
System.out.println();
}
f) Move all even elements to the front, otherwise preserving order
public static void moveEvenToFront(int[] arr)
{
int endOfEvens = 0;
int temp;
for (int i = 0; i < arr.length; i++)
{
© John Wiley & Sons, Inc. All rights reserved.
5
if (arr[i] % 2 == 0) // Even
{
temp = arr[i]; // Save the even number
// Move array element from end of
// evens to current location
for (int j = i; j > endOfEvens; j--)
{
arr[j] = arr[j - 1];
}
arr[endOfEvens] = temp;
endOfEvens++;
}
}
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < randoms.length; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " " );
}
System.out.println();
// Move the evens to the front.
moveEvenToFront(randoms);
// Print again to see new order.
for (int i = 0; i < randoms.length; i++)
{
System.out.print(randoms[i] + " " );
}
System.out.println();
}
g) Return second-largest element in array.
public static int getSecondLargest(int[] arr)
{
// One way to do it: Find maximum once.
int max = arr[0];
for (int i = 1; i < size; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
// 2. Find the max again, ignoring the real max.
© John Wiley & Sons, Inc. All rights reserved.
6
int oldMax = max;
max = arr[0];
for (int i = 1; i < size; i++)
{
if (arr[i] != oldMax)
{
if (arr[i] > max)
{
max = arr[i];
}
}
}
return max;
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < randoms.length; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " " );
}
System.out.println();
// Find the second largest.
System.out.println("The second largest number is " +
+ getSecondLargest(randoms));
}
h) Return true if array is currently in increasing order.
public static boolean inOrder(int[] arr)
{
// Assume they are in order.
boolean ordered = true;
// Loop through array, checking for out
// of order elements
for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i] > arr[i + 1])
{
ordered = false;
}
}
return ordered;
}
public static void main(String[] args)
{
© John Wiley & Sons, Inc. All rights reserved.
7
int[] arrOrder = {1, 2, 3, 4, 5, 6, 7, 8, 9, 42};
int[] arrNotOrder = {2, 1, 3, 4, 5, 6, 7, 8, 9, 42};
// Check if array 1 is ordered or not.
if (inOrder(arrOrder))
{
System.out.println("The array is in order.");
}
else
{
System.out.println("The array is NOT in order.");
}
System.out.println("Expected: The array is in order.");
// Check if array 2 is ordered or not.
if (inOrder(arrNotOrder))
{
System.out.println("The array is in order.");
}
else
{
System.out.println("The array is NOT in order.");
}
System.out.println("Expected: The array is NOT in order.");
}
i) Return true if array contains two adjacent duplicate values.
public static boolean adjacentDupes(int[] arr)
{
// Assume no adjacent dupes.
boolean adjDupes = false;
// Loop through array, checking for duplicates
// next to each other.
for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i] == arr[i + 1])
{
adjDupes = true;
}
}
return adjDupes;
}
public static void main(String[] args)
{
int[] arr1 = {1, 2, 3, 4, 4, 6, 7, 8, 9, 42};
int[] arr2 = {2, 1, 3, 4, 5, 4, 7, 4, 9, 4};
// Check if array 1 has adjacent dupes.
if (adjacentDupes(arr1))
{
System.out.println("Array contains adjacent duplicates.");
}
© John Wiley & Sons, Inc. All rights reserved.
8
else
{
System.out.println("Array does NOT contain adjacent duplicates.");
}
System.out.println("Expected: Array contains adjacent duplicates.");
// Check if array 2 has adjacent dupes.
if (adjacentDupes(arr2))
{
System.out.println("Array contains adjacent duplicates.");
}
else
{
System.out.println("Array does NOT contain adjacent duplicates." );
}
System.out.println("Expected: Array does NOT contain adjacent duplicates.");
}
j) Returns true if array contains duplicate values (not necessarily adjacent).
public static boolean containsDuplicates(int[] arr)
{
// Assume no dupes.
boolean dupes = false;
// Loop through array, checking for duplicates
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i] == arr[j])
{
dupes = true;
}
}
}
return dupes;
}
public static void main(String[] args)
{
int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 42};
int[] arr2 = {2, 1, 3, 4, 5, 4, 7, 4, 9, 4};
// Check if array 1 has dupes.
if (containsDuplicates(arr1))
{
System.out.println("Array contains duplicates.");
}
else
{
System.out.println("Array does NOT contain duplicates.");
}
System.out.println("Expected: Array does NOT contain duplicates.");
// Check if array 2 has dupes.
© John Wiley & Sons, Inc. All rights reserved.
9
if (containsDuplicates(arr2))
{
System.out.println("Array contains duplicates.");
}
else
{
System.out.println("Array does NOT contain duplicates.");
}
System.out.println("Expected: Array contains duplicates.");
P6.3
import java.util.Scanner;
public class LargestAndSmallestInArray
{
public static void main(String[] args)
{
final int LENGTH = 100;
double[] data = new double[LENGTH];
int size = 0;
// Read inputs
System.out.println("Please enter values, Q to quit:");
Scanner in = new Scanner(System.in);
while (in.hasNextDouble() && size < data.length)
{
data[size] = in.nextDouble();
size++;
}
// Find the largest and smallest value
double largest = data[0];
double smallest = data[0];
for (int i = 1; i < size; i++)
{
if (data[i] > largest)
{
largest = data[i];
}
if (data[i] < smallest)
{
smallest = data[i];
}
}
// Print all values, marking the largest and smallest
for (int i = 0; i < size; i++)
{
System.out.print(data[i]);
if (data[i] == largest)
{
© John Wiley & Sons, Inc. All rights reserved.
10
System.out.print(" <== largest value");
}
if (data[i] == smallest)
{
System.out.print(" <== smallest value");
}
System.out.println();
}
}
}
P6.4
import java.util.Scanner;
public class Scores
{
/**
Computes the sum of all values except the smallest in an array.
@param data an array of values
@return the sum of all but the least value in data
*/
public static double sumWithoutSmallest(double[] data, int currentSize)
{
double total = 0;
double smallest = data[0];
for (int i = 0; i < currentSize; i++)
{
if (data[i] < smallest)
{
smallest = data[i];
}
total = total + data[i];
}
return total - smallest;
}
public static void main(String[] args)
{
final int LENGTH = 100;
double[] scores = new double[LENGTH];
int size = 0;
// Read inputs
System.out.println("Please enter scores, Q to quit:");
Scanner in = new Scanner(System.in);
while (in.hasNextDouble() && size < scores.length)
{
scores[size] = in.nextDouble();
size++;
}
if (scores.length == 0)
{
System.out.println("At least one score is required.");
return;
© John Wiley & Sons, Inc. All rights reserved.
11
}
double total = sumWithoutSmallest(scores);
System.out.println("Final score without least one: " + total);
}
}
P6.5
public class RemoveMin
{
public static int removeMin(double[] input, int currentSize)
{
// Find the minimum value first
double min = input[0];
int minPos = 0;
for (int i = 1; i < currentSize; i++)
{
if (input[i] < min)
{
min = input[i];
minPos = i;
}
}
// Now "eliminate" the minimum value
for (int j = minPos; j < currentSize - 1; j++)
{
input[j] = input[j + 1];
}
// Decrement the currentSize
currentSize--;
return currentSize;
}
public static void
{
int[] myArray =
int mySize = 0;
for (int i = 0;
{
myArray[i] =
mySize++;
}
main(String[] args)
new int[10];
i < 6; i++)
(int) (Math.random() * 100) +1;
for (int i = 0; i < mySize; i++)
{
System.out.print(myArray[i] + " ");
}
System.out.println();
removeMin(myArray, mySize);
for (int i = 0; i < mySize; i++)
© John Wiley & Sons, Inc. All rights reserved.
12
{
System.out.print("myArray[i] + " ");
}
System.out.println();
}
}
P6.6
public class AlternatingSum
{
/**
Computes the alternating sum of the values in an array list
@param data an array list of values
@return the alternating sum of the values in data
*/
public static double alternatingSum(double[] data)
{
double total = 0;
for (int i = 0; i < data.length ; i++)
{
if (i % 2 == 0)
{
total += data[i];
}
else
{
total -= data[i];
}
}
return total;
}
public static void main(String[] args)
{
double[] data = { 1, 4, 9, 16, 9, 7, 4, 9, 11 };
double total = alternatingSum(data);
System.out.println("Alternating sum: " + total);
}
}
P6.7
import java.util.Arrays;
public class ReverseElements
{
/**
Reverses an array.
@param data the input array
@return an array with the elements of data in reverse order
*/
public static double[] reverse(double[] data)
© John Wiley & Sons, Inc. All rights reserved.
13
{
double[] revData = Arrays.copyOf(data, data.length);
int j = 0;
for (int i = data.length - 1; i >= 0; i--)
{
revData[j] = data[i];
j++;
}
return revData;
}
public static void main(String[] args)
{
double[] data = { 1, 4, 9, 16, 9, 7, 4, 9, 11 };
double[] reversed = reverse(data);
for (int i = 0; i < reversed.length; i++)
{
System.out.print(reversed[i] + " ");
}
System.out.println();
}
}
P6.8
public class Swap
{
public void swapHalves(int[] a)
{
int i = 0;
int j = a.length / 2;
int temp;
while (i < a.length / 2)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j++;
}
}
public static void main(String[] args)
{
int[] myArray= {1, 4, 9, 16, 9, 7, 4, 11};
swapHalves(myArray);
System.out.println("Printing the new array..." );
for (int i = 0; i < myArray.length; i++)
{
System.out.print("myArray[i] + " ");
}
System.out.println();
}
© John Wiley & Sons, Inc. All rights reserved.
14
}
P6.9
public class BooleanEquals
{
public static boolean equals(int[] a, int[] b)
{
if (a.length != b.length)
{
return false;
}
for (int i = 0; i < a.length; i++)
{
if (a[i] != b[i])
{
return false;
}
}
return true;
}
public static
{
int[] arr1
int[] arr2
int[] arr3
int[] arr4
void main(String[] args)
=
=
=
=
{1,
{1,
{1,
{1,
2,
2,
2,
2,
3,
3,
3,
3,
4,
4,
4,
4,
5,
5,
5,
5,
6,
6,
6,
4,
7,
7,
7,
7,
8};
8};
8, 9};
8};
System.out.print("Arrays 1 and 2 are ");
if (!equals(arr1, arr2))
{
System.out.print("not ");
}
System.out.println("equal." );
System.out.print("Arrays 1 and 3 are ");
if (!equals(arr1, arr3))
{
System.out.print("not ");
}
System.out.println("equal." );
System.out.print("Arrays 1 and 4 are ");
if (!equals(arr1, arr4))
{
System.out.print("not ");
}
System.out.println("equal." );
}
}
P6.10
© John Wiley & Sons, Inc. All rights reserved.
15
public class SetChecker
{
public static boolean isIn(int e, int[] b)
{
for (int i = 0; i < b.length; i++)
{
if (e == b[i])
{
return true;
}
}
return false;
}
public static boolean sameSet(int[] a, int[] b)
{
for (int i = 0; i < a.length; i++)
{
if (!isIn(a[i], b))
{
return false;
}
}
for (int i = 0; i < b.length; i++)
{
if (!isIn(b[i], a))
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
int[] a = {1, 4, 9, 16, 9, 7, 4, 9, 11};
int[] b = {11, 11, 7, 9, 16, 4, 1};
System.out.print("The elements of the arrays a and b ");
if (!sameSet(a, b))
{
System.out.print("do not ");
}
System.out.println("form the same set." );
}
}
P6.11
public class Count
{
public static boolean count(int e, int[] b)
{
© John Wiley & Sons, Inc. All rights reserved.
16
int count = 0;
for (int i = 0; i < b.length; i++)
{
if (e == b[i])
{
count++;
}
}
return count;
}
// This method assumes that the two array arguments
// are the same size.
public static boolean sameElements(int[] a, int[] b)
{
for (int i = 0; i < a.length; i++)
{
if (count(a[i], a) != count(a[i], b))
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
int[] a = {1, 4, 9, 16, 9, 7, 4, 9, 11};
int[] b = {11, 1, 4, 9, 16, 9, 7, 4, 9};
System.out.print("The arrays a and b ");
if (!sameElements(a, b))
{
System.out.print("do not ");
}
System.out.println("have the same elements." );
}
}
P6.12
public class PrintRun
{
/**
Makes an array with n random die (1-6) tosses
@param n the number of tosses to simulate
@return an array with n random die tosses in it
*/
public static int[] generateDieTosses(int n)
{
int[] tosses = new int[n];
for (int i = 0; i < n; i++)
© John Wiley & Sons, Inc. All rights reserved.
17
{
tosses[i] = (int) (Math.random() * 6 + 1);
}
return tosses;
}
/**
Prints values in array by marking runs in parentheses.
@param values the input array to print
*/
public static void printRun(int[] values)
{
boolean inRun = false;
int previousValue = values[0];
for (int i = 0; i < values.length - 1; i++)
{
if (inRun)
{
if (values[i] != previousValue)
{
System.out.print(")");
inRun = false;
}
System.out.print(" ");
}
else
{
if (values[i] == values[i + 1])
{
System.out.print(" (");
inRun = true;
}
else
{
System.out.print(" ");
}
}
previousValue = values[i];
System.out.print(values[i]);
}
if (inRun && values[values.length - 1] == previousValue)
{
System.out.print(" " + values[values.length - 1] + ")");
}
else if (inRun && values[values.length - 1] != previousValue)
{
System.out.print(") " + values[values.length - 1]);
}
else
{
System.out.print(" " + values[values.length - 1]);
}
}
public static void main(String[] args)
{
int[] tosses = generateDieTosses(20);
© John Wiley & Sons, Inc. All rights reserved.
18
printRun(tosses);
}
}
P6.13
public class PrintLongestRun
{
/**
Makes an array with n random die (1-6) tosses
@param n the number of tosses to simulate
@return an array with n random die tosses in it
*/
public static int[] generateDieTosses(int n)
{
int[] tosses = new int[n];
for (int i = 0; i < n; i++)
{
tosses[i] = (int) (Math.random() * 2 + 1);
}
return tosses;
}
/**
Print array with parentheses around element at index up to length long.
@param values the values to print
@param index the index to start parenthesis
@param length of the run of same values
*/
public static void printArrayWithParenthesis(int[] values, int index,
int length)
{
boolean inRun = false;
for (int i = 0; i < values.length; i++)
{
if (inRun)
{
if (length == 0)
{
System.out.print(") " + values[i] + " ");
inRun = false;
}
else
{
System.out.print(" " + values[i]);
}
length--;
}
else if (i == index)
{
inRun = true;
length--;
System.out.print("(" + values[i]);
}
© John Wiley & Sons, Inc. All rights reserved.
19
else
{
System.out.print(values[i] + " ");
}
}
if (length == 0)
{
System.out.print(")");
}
}
/**
Prints values in array by marking runs in parentheses.
@param values the input array to print
*/
public static void printLongestRun(int[] values)
{
boolean inRun = false;
int previousValue = values[0];
int longestRunLength = 0;
int longestRunIndex = -1;
int currentRunLength = 0;
int currentRunIndex = -1;
for (int i = 0; i < values.length - 1; i++)
{
if (inRun)
{
if (values[i] != previousValue)
{
inRun = false;
if (currentRunLength > longestRunLength)
{
longestRunLength = currentRunLength;
longestRunIndex = currentRunIndex;
}
}
else
{
currentRunLength++;
}
}
else
{
if (values[i] == values[i + 1])
{
inRun = true;
currentRunLength = 1;
currentRunIndex = i;
}
}
previousValue = values[i];
}
if (inRun && values[values.length - 1] == previousValue)
{
currentRunLength++;
if (currentRunLength > longestRunLength)
{
© John Wiley & Sons, Inc. All rights reserved.
20
longestRunLength = currentRunLength;
longestRunIndex = currentRunIndex;
}
}
printArrayWithParenthesis(values, longestRunIndex, longestRunLength);
}
public static void main(String[] args)
{
int[] tosses = generateDieTosses(20);
printLongestRun(tosses);
}
}
P6.14
import java.util.Arrays;
public class SortedSequence
{
/**
Makes an array with n random values between 0-99.
@param n the number of tosses to simulate
@return an array with n random die tosses in it
*/
public static int[] generateRandom(int n)
{
int[] tosses = new int[n];
for (int i = 0; i < n; i++)
{
tosses[i] = (int) (Math.random() * 100);
}
return tosses;
}
/**
Prints an array.
@param values the array to print
*/
public static void printArray(int[] values)
{
for (int i = 0; i < values.length; i++)
{
System.out.print(values[i] + " ");
}
System.out.println();
}
public static void main(String[] args)
{
int[] values = generateRandom(20);
printArray(values);
Arrays.sort(values);
printArray(values);
}
© John Wiley & Sons, Inc. All rights reserved.
21
}
P6.15
public class GeneratePermutations
{
/**
Generates an array n elements long with numbers from 1 to n
@param n the length of the resulting array
@return an array with numbers 1 to n
*/
public static int[] generateArray(int n)
{
int[] list = new int[n];
for (int i = 0; i < n; i++)
{
list[i] = (i + 1);
}
return list;
}
/**
Makes an array of permuted values of the input.
@param values input values, this array is empty after the call
@return a permutation of values
*/
public static int[] permuteArray(int[] values)
{
int[] permutation = new int[values.length];;
int currentSize = values.length;
for (int i = 0; i < values.length; i++)
{
int randomIndex = (int) (Math.random() * currentSize - 1);
permutation[i] = values[randomIndex];
values[randomIndex] = values[currentSize - 1];
currentSize--;
}
return permutation;
}
/**
Prints the values of an array.
@param values values to print
*/
public static void printArray(int[] values)
{
for (int i = 0; i < values.length; i++)
{
System.out.print(values[i] + " ");
}
System.out.println();
}
© John Wiley & Sons, Inc. All rights reserved.
22
public static void main(String[] args)
{
int[] values = generateArray(10);
System.out.println("The original list: ");
printArray(values);
for (int i = 1; i <= 10; i++)
{
System.out.print("Permutation " + i + ": ");
values = permuteArray(values);
printArray(values);
}
}
}
P6.16
public class StallSimulation
{
public static final int STALL_NUMBER = 10;
/**
Prints arrays such that _ if element is false and X if element is true
@param stalls array of boolean inputs
*/
public static void printStalls(boolean[] stalls)
{
for (int i = 0; i < stalls.length; i++)
{
if (stalls[i])
{
System.out.print("X ");
}
else
{
System.out.print("_ ");
}
}
System.out.println();
}
/**
Calculates the index in the middle of the longest run of "false"s
@param stalls array indicating if a stall is occupied
@return index of middle of longest run of falses in stalls
*/
public static int nextStall(boolean[] stalls)
{
int longestIndex = -1;
int longestRun = 0;
int currentIndex = -1;
int currentRun = 0;
boolean inRun = false;
for (int i = 0; i < stalls.length; i++)
{
if (inRun && stalls[i])
© John Wiley & Sons, Inc. All rights reserved.
23
{
inRun = false;
if (currentRun >= longestRun)
{
longestRun = currentRun;
longestIndex = currentIndex;
}
}
else if (!inRun && !stalls[i])
{
inRun = true;
currentIndex = i;
currentRun = 1;
}
else if (inRun && !stalls[i])
{
currentRun++;
}
}
if (inRun)
{
if (currentRun >= longestRun)
{
longestRun = currentRun;
longestIndex = currentIndex;
}
}
return (longestRun - 1) / 2 + longestIndex;
}
public static void main(String[] args)
{
boolean[] stalls = new boolean[STALL_NUMBER];
for (int i = 0; i < stalls.length; i++)
{
stalls[nextStall(stalls)] = true;
printStalls(stalls);
}
}
}
P6.17
import java.util.ArrayList;
import java.util.Scanner;
public class RandomInt
{
public static int randInt(int a, int b)
{
return (int) (Math.random() * (b - a + 1)) + a;
}
public static ArrayList<Integer> createPiles()
{
© John Wiley & Sons, Inc. All rights reserved.
24
// Start with 45 cards
int numOfCards = 45;
// Use an array list to hold the "piles" created.
// Each pile will be a number of cards stored
// in an element of the array list.
ArrayList<Integer> piles = new ArrayList<Integer>();
// Generate random numbers of cards for each pile.
// Reduce the number of cards in the "deck" by
// the size of the pile just created.
while (numOfCards > 0)
{
int temp = randInt(1, numOfCards);
numOfCards = numOfCards - temp;
piles.add(temp);
}
// Print the initial pile configuration.
System.out.println("The initial piles are: " );
for (int i = 0; i < piles.size(); i++)
{
System.out.print(piles.get(i) + " ");
}
System.out.println();
// Send the initial array list back
return piles;
}
public static ArrayList<Integer> removeZeros(ArrayList<Integer> p)
{
// The easy way: Create a new array list and
// only copy the non-zero numbers into it.
ArrayList<Integer> copy = new ArrayList<Integer>();
for (int i = 0; i < p.size(); i++)
{
if (p.get(i) != 0)
{
copy.add(p.get(i));
}
}
// Return the newly created array list
return copy;
}
public static ArrayList<Integer> nextRound(ArrayList<Integer> p)
{
// Number of cards in the pile to be created
// is the size of the array list
int numCards = p.size();
ArrayList<Integer> pNew = new ArrayList<Integer>(p);
// Take one card from each existing pile
for (int i = 0; i < pNew.size(); i++)
© John Wiley & Sons, Inc. All rights reserved.
25
{
int newValue = pNew.get(i) - 1;
pNew.set(i, newValue);
}
// Remove any zero piles (piles with no cards)
pNew = new ArrayList<Integer>(removeZeros(pNew));
// Add new pile
pNew.add(numCards);
return pNew;
}
public static void printPiles(ArrayList<Integer> p)
{
System.out.println("The new piles are: ");
for (int i = 0; i < p.size(); i++)
{
System.out.print(p.get(i) + " ");
}
System.out.println();
}
public static boolean finalConfig(ArrayList<Integer> p)
{
// There have to be 9 piles to win, so
// if not, might as well return false
// and be done with it.
if (p.size() != 9)
{
return false;
}
else // There are 9 piles
{
// If no duplicates, we have a winner!
// There has to be 9 piles with no dupes
// to win.
boolean dupes = false;
for (int i = 0; i < p.size(); i++)
{
for (int j = i + 1; j < p.size(); j++)
{
if (p.get(i) == p.get(j))
{
dupes = true;
}
}
}
if (dupes)
{
return false;
}
else
{
return true;
}
© John Wiley & Sons, Inc. All rights reserved.
26
}
}
public static void main(String[] args)
{
ArrayList<Integer> piles = createPiles();
while (!finalConfig(piles))
{
piles = nextRound(piles);
printPiles(piles);
}
}
}
P6.18
import java.util.Scanner;
public class MagicSquares
{
public static final int N = 4;
/**
Reads a "magic square" from input
@return numbers input arranged in an NxN array
*/
public static int[][] readSquare()
{
int[][] square = new int[N][N];
Scanner in = new Scanner(System.in);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
int number = in.nextInt();
square[i][j] = number;
}
}
return square;
}
/**
Determines sum from upper left to lower right diagonal.
@param square an NxN square of numbers
@return value of upper left to lower right sum
*/
public static int leftRightDiagonalSum(int[][] square)
{
int sum = 0;
for (int i = 0; i < N; i++)
{
sum += square[i][i];
}
return sum;
© John Wiley & Sons, Inc. All rights reserved.
27
}
/**
Determines sum from upper right to lower left diagonal.
@param square an NxN square of numbers
@return value of upper left to lower right sum
*/
public static int rightLeftDiagonalSum(int[][] square)
{
int sum = 0;
for (int i = 0; i < N; i++)
{
sum += square[i][N - i - 1];
}
return sum;
}
/**
Determines the sum of the given column.
@param square input magic square
@param columnNumber which column to sum
@return sum of column columnNumber in square
*/
public static int columnSum(int[][] square, int columnNumber)
{
int sum = 0;
for (int i = 0; i < N; i++)
{
sum += square[i][columnNumber];
}
return sum;
}
/**
Determines the sum of the given row
@param square input magic square
@param rowNumber which column to sum
@return sum of row rowNumber in square
*/
public static int rowSum(int[][] square, int rowNumber)
{
int sum = 0;
for (int i = 0; i < N; i++)
{
sum += square[rowNumber][i];
}
return sum;
}
/**
Determines if the square has the appropriate 1..N numbers in it.
@param square an NxN square of numbers
@return true if contains 1..N, false otherwise
*/
public static boolean correctNumbers(int[][] square)
{
boolean[] seenNumber = new boolean[N * N];
© John Wiley & Sons, Inc. All rights reserved.
28
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
int number = square[i][j];
if (number < 1 || number > (N * N))
{
return false;
}
else if (seenNumber[number - 1])
{
return false;
}
else
{
seenNumber[number - 1] = true;
}
}
}
return true;
}
public static boolean validMagicSquare(int[][] square)
{
if (!correctNumbers(square))
{
return false;
}
// get the base sum from the lr diagonal
int baseSum = leftRightDiagonalSum(square);
if (baseSum != rightLeftDiagonalSum(square))
{
return false;
}
// check columns
for (int i = 0; i < N; i++)
{
if (baseSum != columnSum(square, i))
{
return false;
}
}
// check rows
for (int i = 0; i < N; i++)
{
if (baseSum != rowSum(square, i))
{
return false;
}
}
// if we got here, all the sums match
return true;
}
© John Wiley & Sons, Inc. All rights reserved.
29
public static void main(String[] args)
{
System.out.println("Please enter " + (N * N) + " numbers: ");
int[][] square = readSquare();
if (validMagicSquare(square))
{
System.out.println("It's a magic square!");
}
else
{
System.out.println("Not a magic square!");
}
}
}
P6.19
Set row = n - 1, column = n / 2.
For k = 1 ... n*n
Place k at [row][column].
Increment row and column.
If the row or column is n, replace it with 0.
If the element at [row][column] has already been filled
Set row and column to their previous values.
Decrement row.
import java.util.Scanner;
public class MakeMagicSquare
{
public static void printMagicSquare(int[][] square)
{
for (int i = 0; i < square.length; i++)
{
for (int j = 0; j < square[i].length; j++)
{
System.out.printf("%3d", square[i][j]);
}
System.out.println();
}
}
public static int[][] makeMagicSquare(int n)
{
int[][] square = new int[n][n];
int row = n - 1;
int column = n / 2;
for (int k = 1; k <= (n * n); k++)
{
© John Wiley & Sons, Inc. All rights reserved.
30
square[row][column] = k;
row = (row + 1) % n;
column = (column + 1) % n;
if (square[row][column] != 0)
{
column = (column - 1 + n) % n;
row = (row - 2 + n) % n;
}
}
return square;
}
public static void main(String[] args)
{
System.out.println("Enter an odd number: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] square = makeMagicSquare(n);
printMagicSquare(square);
}
}
P6.20
final static int ROWS = 4;
final static int COLS = 4;
public static double neighborAverage(int[][] values, int row, int column)
{
int i = row;
int j = column;
double total = 0;
int count = 0;
if (i == 0)
{
if (j == 0)
{
total = values[i][j + 1]
+ values[i + 1][j]
+ values[i + 1][j + 1];
count = 3;
}
if ((j > 0) && (j != COLS - 1))
{
total = values[i][j - 1]
+ values[i][j + 1]
+ values[i + 1][j]
+ values[i + 1][j + 1]
+ values[i + 1][j - 1];
count = 5;
© John Wiley & Sons, Inc. All rights reserved.
31
}
if ((j > 0) && (j == COLS - 1))
{
total = values[i][j - 1]
+ values[i + 1][j]
+ values[i + 1][j - 1];
count = 3;
}
}
else if (i == ROWS -1)
{
if (j == 0)
{
total = values[i - 1][j]
+ values[i - 1] [j + 1]
+ values[i][j + 1];
count = 3;
}
if ((j > 0) && (j != COLS - 1))
{
total = values[i][j - 1]
+ values[i][j + 1]
+ values[i - 1][j]
+ values[i - 1][j + 1]
+ values[i - 1][j - 1];
count = 5;
}
if ((j > 0) && (j == COLS - 1))
{
total = values[i][j - 1]
+ values[i - 1][j]
+ values[i - 1][j - 1];
count = 3;
}
}
else if (j == 0)
{
if (i == 0)
{
total = values[i][j + 1]
+ values[i + 1][j]
+ values[i + 1][j + 1];
count = 3;
}
if ((i > 0) && (i != ROWS - 1))
{
total = values[i - 1][j]
+ values[i][j + 1]
+ values[i - 1][j + 1]
+ values[i + 1][j + 1]
+ values[i + 1][j];
count = 5;
© John Wiley & Sons, Inc. All rights reserved.
32
}
if ((i > 0) && (i == ROWS - 1))
{
total = values[i - 1][j + 1]
+ values[i - 1][j]
+ values[i][j + 1];
count = 3;
}
}
else if (j == COLS -1)
{
if (i == 0)
{
total = values[i][j-1]
+ values[i + 1][j-1]
+ values[i + 1][j];
count = 3;
}
if ((i > 0) && (i != ROWS - 1))
{
total = values[i - 1][j]
+ values[i][j - 1]
+ values[i - 1][j-1]
+ values[i + 1][j - 1]
+ values[i + 1][j];
count = 5;
}
if ((i>0) && (i == ROWS - 1))
{
total = values[i - 1][j]
+ values[i - 1][j-1]
+ values[i][j - 1];
count = 3;
}
}
else
{
total = total +
+ values[i + 1][j]
+ values [i + 1][j +
+ values [i + 1][j + values [i][j - 1]
+ values [i][j + 1]
+ values [i - 1][j]
+ values [i - 1][j +
+ values [i - 1][j count = 8;
}
1]
1]
1]
1];
return total / count;
}
© John Wiley & Sons, Inc. All rights reserved.
33
P6.21
import java.util.ArrayList;
import java.util.Scanner;
public class BarChart
{
/**
Read a sequence of positive integers from input and construct an
array list out of them.
@return an array list of values from user input
*/
public static ArrayList<Integer> readValues()
{
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("Enter a sequence of positive integers. "
+ "Enter a negative value to quit: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while (n >= 0)
{
list.add(n);
n = in.nextInt();
}
return list;
}
/**
Return the largest element in the array list.
@param list the input list
@return the largest element in list
*/
public static int findMax(ArrayList<Integer> list)
{
int max = list.get(0);
for (int x : list)
{
if (x > max)
{
max = x;
}
}
return max;
}
/**
Prints a chart of asterisks based on the input list and largest
element in the list.
@param list the input list
*/
public static void printBarChart(ArrayList<Integer> list)
{
© John Wiley & Sons, Inc. All rights reserved.
34
int max = findMax(list);
for (int i = 0; i < list.size(); i++)
{
int n = list.get(i);
// the 40.0 below comes from the maximum number of stars to print
int stars = (int) (40.0 * n / max);
for (int j = 0; j < stars; j++)
{
System.out.print("*");
}
System.out.println();
}
}
public static void main(String[] args)
{
ArrayList<Integer> list = readValues();
printBarChart(list);
}
}
P6.22
Note: “Work correctly when data contains negative values" is assumed to mean that negative values
should somehow extend the bar to the left as in the example below
**********
********************
************************
**********
********************
******************************
****************************************
import java.util.ArrayList;
public class BarChartWithNegatives
{
/**
Read a sequence of positive integers from input and construct an
array list out of them.
@return an array list of values from user input
*/
public static ArrayList<Integer> readValues()
{
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("Enter a sequence of positive integers. "
+ "Enter a 'q' to quit: ");
Scanner in = new Scanner(System.in);
while (in.hasNextInt())
{
list.add(in.nextInt());
© John Wiley & Sons, Inc. All rights reserved.
35
}
return list;
}
/**
Return the largest element in the array list.
@param list the input list
@return the largest element in list
*/
public static int findMax(ArrayList<Integer> list)
{
int max = list.get(0);
for (int x : list)
{
if (x > max)
{
max = x;
}
}
return max;
}
/**
Return the smallest element in the array list.
@param list the input list
@return the smallest element in list
*/
public static int findMin(ArrayList<Integer> list)
{
int min = list.get(0);
for (int x : list)
{
if (x < min)
{
min = x;
}
}
return min;
}
/**
Prints a chart of asterisks based on the input list and largest
and smallest elements in the list.
@param values the input list
*/
public static void printBarChart(ArrayList<Integer> values)
{
int max = findMax(values);
int min = findMin(values);
int posStars = 40;
int negStars = 0;
if (Math.abs(min) > max)
{
negStars = 40;
posStars = (int) (40.0 * max / Math.abs(min));
}
© John Wiley & Sons, Inc. All rights reserved.
36
else if (min < 0)
{
negStars = (int) (40.0 * Math.abs(min) / max);
}
for (int i = 0; i < values.size(); i++)
{
int n = values.get(i);
if (n >= 0)
{
int stars = (int) ((double) posStars * n / max);
for (int j = 0; j < negStars; j++)
{
System.out.print(" ");
}
for (int j = 0; j < stars; j++)
{
System.out.print("*");
}
System.out.println();
}
else
{
int stars = (int) ((double) negStars * n / min);
for (int j = 0; j < negStars - stars; j++)
{
System.out.print(" ");
}
for (int j = 0; j < stars; j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
public static void main(String[] args)
{
ArrayList<Integer> list = readValues();
printBarChart(list);
}
}
P6.23
import java.util.ArrayList;
import java.util.Scanner;
public class BarChartWithCaptions
{
/**
Read a sequence of positive integers and names from input and construct
an array list out of them.
@param values an initially empty list that gets the positive values
© John Wiley & Sons, Inc. All rights reserved.
37
from input
@param captions an initially empty list that gets the captions
associated with the values
*/
public static void readValues(ArrayList<Integer> values,
ArrayList<String> captions)
{
values.clear();
captions.clear();
System.out.println("Enter a sequence of positive integers followed by name.
+ "Enter a negative value to quit: ");
"
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while (n >= 0)
{
values.add(n);
String caption = in.next();
captions.add(caption);
n = in.nextInt();
}
}
/**
Return the largest element in the array list.
@param list the input list
@return the largest element in list
*/
public static int findMax(ArrayList<Integer> list)
{
int max = list.get(0);
for (int x : list)
{
if (x > max)
{
max = x;
}
}
return max;
}
/**
Return the length of the longest element in the array list.
@param list the input list
@return the length of the longest element in list
*/
public static int findLongestCaption(ArrayList<String> captions)
{
int max = captions.get(0).length();
for (String x : captions)
{
if (x.length() > max)
{
max = x.length();
}
© John Wiley & Sons, Inc. All rights reserved.
38
}
return max;
}
/**
Prints a chart of asterisks based on the input list and largest
element in the list.
@param values the input list
*/
public static void printBarChart(ArrayList<Integer> values,
ArrayList<String> captions)
{
int max = findMax(values);
int longest = findLongestCaption(captions);
for (int i = 0; i < values.size(); i++)
{
int n = values.get(i);
String caption = captions.get(i);
int spaces = longest - caption.length();
for (int j = 0; j < spaces; j++)
{
System.out.print(" ");
}
System.out.print(caption + " ");
// the 40.0 below comes from the maximum number of stars to print
int stars = (int) (40.0 * n / max);
for (int j = 0; j < stars; j++)
{
System.out.print("*");
}
System.out.println();
}
}
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<String> captions = new ArrayList<String>();
readValues(list, captions);
printBarChart(list, captions);
}
}
P6.24
Note: The initial seating chart in this solution is generated as shown in the example. the solution also
assumes that the user will enter a row and seat which start at 1 and where row 1 is the bottom front
row.
import java.util.Scanner;
© John Wiley & Sons, Inc. All rights reserved.
39
public class SeatingChart
{
/**
Prints the price of seats in a grid like pattern.
@param seats a 2D array of prices
*/
public static void printSeats(int[][] seats)
{
for (int i = 0; i < seats.length; i++)
{
for (int j = 0; j < seats[i].length; j++)
{
System.out.printf("%3d", seats[i][j]);
}
System.out.println();
}
}
/**
Marks a seat with the price given to 0.
@param seats the array of seat prices
@param price the price to mark to zero
*/
public static void sellSeatByPrice(int[][] seats, int price)
{
for (int i = 0; i < seats.length; i++)
{
for (int j = 0; j < seats[i].length; j++)
{
if (seats[i][j] == price)
{
seats[i][j] = 0;
return;
}
}
}
System.out.println("Sorry, no seat found with that price.");
}
/**
Marks a seat based on a given row and seat number from input.
@param seats the array of seat prices
*/
public static void sellSeatByNumber(int[][] seats)
{
System.out.println("Enter the row and seat number you want: ");
Scanner in = new Scanner(System.in);
int row = in.nextInt();
if (row > 0 && row <= seats.length)
{
int seat = in.nextInt();
if (seat > 0 && seat <= seats[seats.length - row].length)
{
if (seats[seats.length - row][seat - 1] != 0)
{
seats[seats.length - row][seat - 1] = 0;
}
© John Wiley & Sons, Inc. All rights reserved.
40
else
{
System.out.println("Sorry, seat already occupied.");
}
}
else
{
System.out.println("Sorry, invalid row.");
}
}
else
{
System.out.println("Sorry, invalid row.");
}
}
public static void main(String[] args)
{
// initial values come from problem description
int[][] seats = { { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 },
{ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 },
{ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 },
{ 10, 10, 20, 20, 20, 20, 20, 20, 10, 10 },
{ 10, 10, 20, 20, 20, 20, 20, 20, 10, 10 },
{ 10, 10, 20, 20, 20, 20, 20, 20, 10, 10 },
{ 20, 20, 30, 30, 40, 40, 30, 30, 20, 20 },
{ 20, 30, 30, 40, 50, 50, 40, 30, 30, 20 },
{ 30, 40, 50, 50, 50, 50, 50, 50, 40, 30 } };
printSeats(seats);
System.out.println("Pick by <s>eat or <p>rice or <q> to quit: ");
Scanner in = new Scanner(System.in);
String choice = in.next();
while (!choice.equals("q"))
{
if (choice.equals("s"))
{
sellSeatByNumber(seats);
}
else
{
// pick by price
System.out.println("What price do you want to buy?");
int price = in.nextInt();
sellSeatByPrice(seats, price);
}
printSeats(seats);
System.out.println("Pick by <s>eat or <p>rice or <q> to quit: ");
choice = in.next();
}
}
}
P6.25
© John Wiley & Sons, Inc. All rights reserved.
41
import java.util.Scanner;
public class PlayTicTacToe
{
/**
Checks if player has won tic-tac-toe along diagonal lines.
@param board a 3x3 array containing 0, 1, 2, values indicating
blanks or player numbers
@param player the player to check for a winning sequence of marks
@return true if player won, false otherwise
*/
public static boolean wonDiagonal(int[][] board, int player)
{
int count = 0;
// check one diagonal
for (int i = 0; i < 3; i++)
{
if (board[i][i] == player)
{
count++;
}
}
if (count == 3)
{
return true;
}
else
{
count = 0;
}
// check other diagonal
for (int i = 0; i < 3; i++)
{
if (board[i][2 - i] == player)
{
count++;
}
}
if (count == 3)
{
return true;
}
else
{
return false;
}
}
/**
Checks if player has won tic-tac-toe along straight lines.
@param board a 3x3 array containing 0, 1, 2, values indicating
blanks or player numbers
@param player the player to check for a winning sequence of marks
@return true if player won, false otherwise
© John Wiley & Sons, Inc. All rights reserved.
42
*/
public static boolean wonStraightLines(int[][] board, int player)
{
for (int i = 0; i < 3; i++)
{
int count = 0;
for (int j = 0; j < 3; j++)
{
if (board[i][j] == player)
{
count++;
}
}
if (count == 3)
{
return true;
}
}
for (int i = 0; i < 3; i++)
{
int count = 0;
for (int j = 0; j < 3; j++)
{
if (board[j][i] == player)
{
count++;
}
}
if (count == 3)
{
return true;
}
}
return false;
}
/**
Checks if player has won.
@param board a 3x3 array containing 0, 1, 2, values indicating
blanks or player numbers
@param player the player to check for a winning sequence of marks
@return true if player won, false otherwise
*/
public static boolean win(int[][] board, int player)
{
if (wonDiagonal(board, player) || wonStraightLines(board, player))
{
return true;
}
else
{
return false;
}
}
/**
Draws gameboard, player 1 is X, player 2 is O.
© John Wiley & Sons, Inc. All rights reserved.
43
@param board the gameboard filled with 0, 1, or 2s
*/
public static void drawBoard(int[][] board)
{
System.out.println("|-----|");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i][j] == 1)
{
System.out.print("|X");
}
else if (board[i][j] == 2)
{
System.out.print("|O");
}
else
{
System.out.print("| ");
}
}
System.out.println("|\n|-----|");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int[][] board = new int[3][3];
int player = 2;
drawBoard(board);
while (!win(board, player))
{
if (player == 1)
{
player = 2;
}
else
{
player = 1;
}
System.out.println("Player " + player + " choose a row and column.");
int row = in.nextInt();
int column = in.nextInt();
board[row][column] = player;
drawBoard(board);
}
System.out.println("Player " + player + " wins!");
}
}
© John Wiley & Sons, Inc. All rights reserved.
44
P6.26
public static ArrayList<Integer> append(ArrayList<Integer> a,
ArrayList<Integer> b)
{
ArrayList<Integer> r = a;
for (int i = 0; i < b.size(); i++)
{
r.add(b.get(i));
}
return r;
}
public static void main(String[] args)
{
ArrayList<Integer> a = new ArrayList(5);
ArrayList<Integer> b = new ArrayList(3);
int i;
for (i = 0; i < a.size(); i++)
{
/* Initialize array list a to some values */
a.set(i, i + 3);
}
for (i = 0; i < b.size(); i++)
{
/* Initialize array list b to some values */
b.set(i, i + 2);
}
ArrayList<Integer> c = append(a, b);
System.out.println("Result of append of a and b is ");
for (i = 0; i < c.size(); i++)
{
System.out.println(c.get(i) + " ");
}
}
P6.27
public static ArrayList<Integer> merge(ArrayList<Integer> a,
ArrayList <Integer> b)
{
int i = 0;
int j = 0;
int k = 0;
ArrayList<Integer> c = new ArrayList<Integer>(a.size() + b.size());
while ((i < a.size()) && (j < b.size()))
© John Wiley & Sons, Inc. All rights reserved.
45
{
c.set(k, a.get(i));
c.set(k + 1, b.get(j));
i++;
j++;
k = k + 2;
}
if (i < a.size())
// Have we more a elements to add?
{
while (i < a.size())
{
c.set(k, a.get(i));
i++;
k++;
}
}
else if (j < b.size()) // Have we more b elements to add?
{
while (j < b.size())
{
c.set(k, b.get(j));
j++;
k++;
}
}
return c;
}
public static void main(String[] args)
{
ArrayList <Integer> a = new ArrayList(4);
ArrayList <Integer> b = new ArrayList(5);
int i;
// Initialize array list a to some values
for (i = 0; i < a.size(); i++)
{
a.set(i, (i + 1) * (i + 1));
}
// Initialize array list b to some values
b.set(0, 9);
b.set(1, 7);
b.set(2, 4);
b.set(3, 9);
b.set(4, 11);
ArrayList <Integer> c = merge(a, b);
System.out.println("Result of merge of a and b is ");
for (i = 0; i < c.size(); i++)
{
System.out.println(c.get(i) + " ");
}
}
© John Wiley & Sons, Inc. All rights reserved.
46
P6.28
public static ArrayList<Integer> mergeSorted(ArrayList<Integer> a,
ArrayList<Integer> b)
{
int i = 0;
int j = 0;
int k = 0;
ArrayList<Integer> c = new ArrayList(a.size() + b.size());
while (i < a.size() && j < b.size())
{
if (a.get(i) < b.get(j))
{
c.set(k, a.get(i));
i++;
}
else
{
c.set(k, b.get(j));
j++;
}
k++;
}
// More a elements to add?
if (i < a.size())
{
while (i < a.size())
{
c.set(k, a.get(i));
i++;
k++;
}
}
else if (j < b.size()) // More b elements to add?
{
while (j < b.size())
{
c.set(k, b.get(j));
j++;
k++;
}
}
return c;
}
public static void main(String[] args)
{
ArrayList<Integer> a = new ArrayList(4);
ArrayList<Integer> b = new ArrayList(5);
int i;
// Initialize array list a to some values
© John Wiley & Sons, Inc. All rights reserved.
47
for (i = 0; i < a.size(); i++)
{
a.set(i, (i + 1) * (i + 1));
}
// Initialize array list b to some values
b.set(0, 9);
b.set(1, 7);
b.set(2, 4);
b.set(3, 9);
b.set(4, 11);
ArrayList<Integer> c = mergeSorted(a, b);
System.out.println("Result of merge sort of a and b is " );
for (i = 0; i < c.size(); i++)
{
System.out.println(c.get(i) + " ");
}
}
P6.29
import java.util.*;
public class PetDiscount
{
public static void discount(double[] prices, boolean[] isPet, int nItems)
{
boolean flag = false;
double total = 0.0;
int pets = 0;
if (nItems >= 6)
{
for (int i = 0; i < isPet.length; i++)
{
if (isPet[i] == true)
{
pets++;
flag = true;
}
}
if (flag == true && (numItems – pets) >= 5)
{
for (int i = 0; i < prices.length ; i++)
{
if (isPet[i] == true)
{
total = total + prices[i];
}
else
{
© John Wiley & Sons, Inc. All rights reserved.
48
total = total + prices[i] * .8;
}
}
}
System.out.println("Final price after discount " + total );
}
public static void main(String[] args)
{
double[] prices1 = new double[100];
boolean[] isPet1 = new boolean[100];
Scanner in = new Scanner(System.in);
boolean done = false;
int i = 0;
while (!done)
{
System.out.println("Enter the price, or -1 to quit: " );
double d = in.nextDouble();
if (d == -1)
{
done = true;
}
else
{
if (done == false)
{
prices1[i] = d;
System.out.println("Is it a pet? y/n" );
String t = in.next();
if (t.equals("Y") || t.equals("y"))
{
isPet1[i] = true;
}
else
{
isPet1[i] = false;
}
i++;
}
}
}
discount(prices1, isPet1, i);
}
}
P6.30
import java.util.*;
© John Wiley & Sons, Inc. All rights reserved.
49
public class TopCustomer
{
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
double max = sales.get(0);
String top = " ";
for (int i = 0; i < sales.size(); i++)
{
if (sales.get(i) >= max)
{
max = sales.get(i);
top = customers.get(i);
}
}
return top;
}
public static void main(String[] args)
{
ArrayList<Double> price = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
Scanner in = new Scanner(System.in);
boolean done = false;
int i = 0;
while (!done)
{
System.out.println("Enter the price: " );
double d = in.nextDouble();
if (d == 0)
{
done = true;
}
else
{
price.add(d);
System.out.println("Customer's last name: ");
names.add(in.next());
i++;
}
}
System.out.println("Best customer's name "
+ nameOfBestCustomer(price, names));
}
}
P6.31
import java.util.*;
© John Wiley & Sons, Inc. All rights reserved.
50
public class test1
{
public static ArrayList<String> nameOfBestCustomers(ArrayList<Double> sales,
ArrayList<String> customers, int topN)
{
Arrays.sort(sales.toArray());
ArrayList<String> topnames = new ArrayList<String>();
for (int i = 0; i < topN ; i++)
{
topnames.add(customers.get(sales.indexOf(sales.get(i))));
}
return topnames;
}
public static void main(String[] args)
{
ArrayList<Double> price = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> tn = new ArrayList<String>();
Scanner in = new Scanner(System.in);
boolean done = false;
int i = 0;
while (!done)
{
System.out.println("Enter the price: " );
double d = in.nextDouble();
if (d == 0)
{
done = true;
}
else
{
price.add(d);
System.out.println("Customer's last name " );
names.add(in.next());
i++;
}
}
System.out.println("How many top customers should display? " );
int topN = in.nextInt();
tn = nameOfBestCustomers(price, names, topN);
System.out.println("Best customer's names: " );
for (int k = 0; k < tn.size() ; k++)
{
System.out.println(tn.get(k).toString());
}
}
}
© John Wiley & Sons, Inc. All rights reserved.
51
P6.32
import
import
import
import
import
import
import
import
import
import
import
java.awt.Color;
java.awt.Graphics;
java.io.RandomAccessFile;
java.io.IOException;
java.util.Arrays;
javax.swing.JComponent;
javax.swing.JFileChooser;
javax.swing.JFrame;
javax.swing.JOptionPane;
javax.sound.sampled.AudioSystem;
javax.sound.sampled.Clip;
/**
This program processes a 16 bit uncompressed mono .WAV file.
*/
public class Echo
{
/**
Processes the sound samples. Modify this function to change
the way the sound is processed.
@param samples the sound samples in the sound file
@param size the number of samples
@param sampleRate the number of samples per second
*/
public static void process(int samples[], int sampleRate)
{
int delay = sampleRate / 5;
for (int i = samples.length - 1; i >= delay; i--)
{
samples[i] = samples[i] + samples[i - delay];
}
// Make sure that no values are larger than 32767
// Find the largest value
int max = samples[0];
for (int i = 1; i < samples.length; i++)
{
if (samples[i] > max) { max = samples[i]; }
}
// Scale if necessary
if (max > 32767)
{
for (int i = 0; i < samples.length; i++)
{
samples[i] = samples[i] * 32767 / max;
}
}
© John Wiley & Sons, Inc. All rights reserved.
52
}
// ----------------------------------------------------------------/*
The code below processes a file in the WAV format.
You can use this program to manipulate sound files without
reading or understanding the code below.
The code uses Java features that are introduced in chapter 19,
as well as the internals of the WAV format
(https://ccrma.stanford.edu/courses/422/projects/WaveFormat/)
*/
/**
Gets an unsigned 4-byte integer from a random access file.
@param in the file
@return the integer
*/
public static int getUnsignedInt4(RandomAccessFile in)
throws IOException
{
int result = 0;
int base = 1;
for (int i = 0; i < 4; i++)
{
result = result + in.read() * base;
base = base * 256;
}
return result;
}
/**
Gets an unsigned 2-byte integer from a random access file.
@param in the file
@return the integer
*/
public static int getUnsignedInt2(RandomAccessFile in)
throws IOException
{
int lo = in.read();
int hi = in.read();
return lo + 256 * hi;
}
/**
Gets a signed 2-byte integer from a random access file.
@param in the file
@return the integer
*/
public static int getSignedInt2(RandomAccessFile in)
throws IOException
{
int lo = in.read();
int hi = in.read();
int result = lo + 256 * hi;
if (result >= 32768) { result = result - 65536; }
© John Wiley & Sons, Inc. All rights reserved.
53
return result;
}
/**
Puts a signed 2-byte integer to a random access file.
@param out the file
@param value the integer to put
*/
public static void putSignedInt2(RandomAccessFile out, int value)
throws IOException
{
if (value < 0) { value = value + 65536; }
out.write(value % 256);
out.write(value / 256);
}
public static void main(String[] args) throws Exception
{
JFileChooser chooser = new JFileChooser(".");
if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION)
{
System.out.println("No sound file selected.");
System.exit(1);
}
RandomAccessFile file = new RandomAccessFile(
chooser.getSelectedFile(), "rw");
// Check that we can handle this file
file.seek(20);
int formatType = getUnsignedInt2(file);
if (formatType != 1)
{
System.out.println("Not an uncompressed sound file.");
System.exit(1);
}
int numChannels = getUnsignedInt2(file);
if (numChannels != 1)
{
System.out.println("Not a mono sound file.");
System.exit(1);
}
final int sampleRate = getUnsignedInt2(file);
file.seek(34);
int bitsPerSample = getUnsignedInt2(file);
if (bitsPerSample != 16)
{
System.out.println("Not a 16 bit sound file.");
System.exit(1);
}
// Read data size and allocate data array
file.seek(40);
int dataSize = getUnsignedInt4(file) / 2; // 2 bytes per data
final int[] samples = new int[dataSize];
© John Wiley & Sons, Inc. All rights reserved.
54
// Read sound data
for (int i = 0; i < dataSize; i++)
{
samples[i] = getSignedInt2(file);
}
final int[] original = Arrays.copyOf(samples, dataSize);
// Process sound data
process(samples, sampleRate);
// Write sound data
file.seek(44);
for (int i = 0; i < dataSize; i++)
{
putSignedInt2(file, samples[i]);
}
file.close();
// This is the end of the file processing.
// Next, we show the original and processed wave forms
JFrame frame = new JFrame();
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 200;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent component = new JComponent()
{
public void paintComponent(Graphics graph)
{
int increment = samples.length / getWidth();
// Find the largest value for scaling the displayed values
int largest = 0;
for (int i = 0; i < samples.length; i = i + increment)
{
int sample = Math.abs(samples[i]);
int orig = Math.abs(original[i]);
if (sample > largest) { largest = sample; }
if (orig > largest) { largest = orig; }
}
int x = 0;
for (int i = 0; i < samples.length; i = i + increment)
{
int height = getHeight() / 4;
int y = height - original[i] * height / largest;
graph.drawLine(x, y, x, height);
y = 3 * height - samples[i] * height / largest;
graph.drawLine(x, y, x, 3 * height);
© John Wiley & Sons, Inc. All rights reserved.
55
x++;
}
}
};
frame.add(component);
frame.setVisible(true);
// Now play the sound
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(
chooser.getSelectedFile()));
clip.start();
}
}
P6.33
import java.util.Scanner;
public class Floodmap
{
public static void floodMap(double[][] heights, double waterLevel)
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (heights[i][j] < waterLevel)
{
System.out.print("* ");
}
else
{
System.out.print(" ");
}
}
}
}
public double lowest(double heights[10][10])
{
double min = heights[0][0];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (heights[i][j] < min)
{
min = heights[i][j];
}
}
}
return min;
© John Wiley & Sons, Inc. All rights reserved.
56
}
public double highest(double heights[10][10])
{
double max = heights[0][0];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (heights[i][j] > max)
{
max = heights[i][j];
}
}
}
return max;
}
public void read(double heights[10][10])
{
Scanner in = new Scanner(System.in);
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
heights[i][j] = in.nextDouble();
}
}
}
public static void main(String[] args)
{
System.out.print("Enter height values:" );
double heights[10][10];
read(heights);
double min = lowest(heights);
double max = highest(heights);
final int STEPS = 10;
for (int i = 0; i < STEPS; i++)
{
floodMap(heights, min + i * (max - min) / (STEPS - 1));
}
}
}
P6.34
import java.util.Scanner;
public class WaveLength
{
/**
Smoothes out an array by averaging values with its neighbors.
@param values an array
© John Wiley & Sons, Inc. All rights reserved.
57
@param size the number of elements in values
*/
public static void smooth(double[] values, int size)
{
double previous = values[0];
values[0] = (values[0] + values[1]) / 2;
for (int i = 1; i < size - 1; i++)
{
double average = (previous + values[i] + values[i + 1]) / 3;
previous = values[i]; // save before overwriting
values[i] = average;
}
values[size - 1] = (previous + values[size - 1]) / 2;
}
/**
Prints an array.
@param a an array
*/
public static void print(double[] a)
{
for (int i = 0; i < a.length; i++)
{
System.out.println(a[i] + " " );
}
System.out.println();
}
public static void main(String[] args)
{
final int SIZE = 100;
double[] a = new double[SIZE];
for (int i = 0; i < SIZE; i++)
{
a[i] = 1 + i / 100.0;
// Add some noise between -0.01 and .01
a[i] = a[i] + (1 - 2 * (Math.random() * 1.0 / 10000)) / 100;
}
print(a);
smooth(a, SIZE);
print(a);
}
}
P6.35
import
import
import
import
import
import
import
java.awt.Color;
java.awt.Graphics;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.JFrame;
javax.swing.JComponent;
javax.swing.Timer;
© John Wiley & Sons, Inc. All rights reserved.
58
/*
A drawing of a sine wave.
*/
public class SineWaveAnimation
{
public static void draw(Graphics g, int frame)
{
final int STEPS = 360;
final int HEIGHT = 300;
for (int c = 0; c < STEPS; c++)
{
double y = Math.sin(Math.toRadians(c - frame));
g.drawLine(c, HEIGHT / 2, c, (int)(HEIGHT / 2 + y * HEIGHT / 2));
}
}
public static void main(String[] args)
{
// Do not look at the code in the main method
// Your code will go into the draw method above
JFrame frame = new JFrame();
final int FRAME_WIDTH = 400;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JComponent component = new JComponent()
{
private int frame = 0;
public void paintComponent(Graphics graph)
{
frame++;
draw(graph, frame);
}
};
ActionListener timerListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
component.repaint();
}
};
final int DELAY = 25; // 25 milliseconds between frames
Timer t = new Timer(DELAY, timerListener);
t.start();
frame.add(component);
frame.setVisible(true);
}
}
© John Wiley & Sons, Inc. All rights reserved.
59
P6.36
import
import
import
import
java.awt.Color;
java.awt.Graphics;
javax.swing.JFrame;
javax.swing.JComponent;
/*
This program draws an oscillating spring.
*/
public class OscillatingSpring
{
public static void draw(Graphics g)
{
double dt = 0.01;
double
double
double
double
x
k
m
v
=
=
=
=
0.5;
10.0;
1.0;
0.0;
final int ITERATIONS = 10; // 10 * 0.01 sec = 0.1 sec
final int WIDTH = 400;
for (int c = 0; c < WIDTH; c += 2)
{
for (int i = 0; i < ITERATIONS; i++)
{
double a = - k * x / m;
v += a * dt;
x += v * dt;
}
g.drawLine(c, 0, c, (int)(x * 100) + 100);
}
}
public static void main(String[] args)
{
// Do not look at the code in the main method
// Your code will go into the draw method above
JFrame frame = new JFrame();
final int FRAME_WIDTH = 400;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent component = new JComponent()
{
public void paintComponent(Graphics graph)
{
draw(graph);
© John Wiley & Sons, Inc. All rights reserved.
60
}
};
frame.add(component);
frame.setVisible(true);
}
}
P6.37
import
import
import
import
java.awt.Color;
java.awt.Graphics;
javax.swing.JFrame;
javax.swing.JComponent;
/*
This program draws a checkerboard.
*/
public class Checkerboard
{
public static void draw(Graphics g)
{
final int width = 20;
g.setColor(Color.BLUE);
int y = 0;
int x = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
g.fillRect(x, y, width, width);
x = x + 2 * width;
}
x = width;
y = y + width;
for (int j = 0; j < 4; j++)
{
g.fillRect(x, y, width, width);
x = x + 2 * width;
}
x = 0;
y = y + width;
}
}
public static void main(String[] args)
{
// Do not look at the code in the main method
// Your code will go into the draw method above
JFrame frame = new JFrame();
final int FRAME_WIDTH = 400;
© John Wiley & Sons, Inc. All rights reserved.
61
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent component = new JComponent()
{
public void paintComponent(Graphics graph)
{
draw(graph);
}
};
frame.add(component);
frame.setVisible(true);
}
}
P6.38
import
import
import
import
java.awt.Color;
java.awt.Graphics;
javax.swing.JFrame;
javax.swing.JComponent;
/*
This program draws a sine wave
*/
public class SineWave
{
public static void draw(Graphics g)
{
final int HEIGHT = 300;
for (int c = 0; c < 360; c = c + 5)
{
double y = Math.sin(Math.toRadians(c));
int h = (int)(y * HEIGHT / 2);
if (h > 0)
{
g.fillRect(c, HEIGHT / 2 - h, 3, h);
}
else
{
g.fillRect(c, HEIGHT / 2, 3, -h);
}
}
}
public static void main(String[] args)
{
// Do not look at the code in the main method
// Your code will go into the draw method above
JFrame frame = new JFrame();
final int FRAME_WIDTH = 400;
© John Wiley & Sons, Inc. All rights reserved.
62
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent component = new JComponent()
{
public void paintComponent(Graphics graph)
{
draw(graph);
}
};
frame.add(component);
frame.setVisible(true);
}
}
© John Wiley & Sons, Inc. All rights reserved.
63