created 05/31/03; revised 07/07/07, 11/09/2012, 07/15/2018

# Chapter 61 Programming Exercises

## Exercise 1 — Sum of Even, Odd, and All Elements

Complete the following program so that it computes the sum of all the elements of the array, the sum of the even elements, and the sum of the odd elements. Assume that all the numbers are zero or positive. Even integers are those for which `N%2` is zero.

```import java.io.* ;

class ThreeSums
{

public static void main ( String[] args )
{
int[] data = {3, 2, 5, 7, 9, 12, 97, 24, 54};

// declare and initialize three sums

// compute the sums
for ( int index=0; index < data.length; index++)
{
}

// write out the three sums
System.out.println(  );

}
}
```

## Exercise 2 — Two Largest Elements

Complete the following program so that it computes and writes out the two largest elements in the array. Use only one loop and don't change any elements of the array.

```import java.io.* ;

class TwoLargest
{

public static void main ( String[] args )
{
int[] data = {3, 1, 5, 7, 4, 12, -3, 8, -2};

// declare and initialize variables for the two largest

// compute the two largest
for ( int index= ; index < data.length; index++)
{
}

// write out the two largest
System.out.println(  );

}
}
```

Change the program to use an enhanced for loop, if you want.

## Exercise 3 — Closest to Zero

Complete the following program so that it computes and writes out the element in the array that is closest to zero.

```import java.io.* ;

class NearlyZero
{

public static void main ( String[] args )
{
int[] data = {3, 1, 5, 7, 4, 12, -3, 8, -2};

// declare and initialize variables

// find the element nearest to zero
for (  )
{
}

// write out the element nearest to zero
System.out.println(  );

}
}
```

## Exercise 4 — Reversal of Elements

Complete the following program so that it reverses the order of the values in `data`, then prints it out.

In the first version of the program there is only one array and its values are reversed with some fairly tricky programming.

```import java.io.* ;

class ReverserVersion1
{

public static void main ( String[] args )
{
int[] data = {1,2,3,4,5,6,7,8,9,10,11,12,13,14};

// reverse the data
for ( int j=0; j < be careful here; j++)
{

}

// write out the new data
for ( int j=0; j < data.length; j++)
{

}

}
}
```

Now write another program that uses two arrays. The first array `data` is not changed. The second array `result` gets the elements of `data` in reversed order.

```import java.io.* ;

class ReverserVersion2
{

public static void main ( String[] args )
{
int[] data = {1,2,3,4,5,6,7,8,9,10,11,12,13,14};
int[] result =

// copy the data in reversed order to result
for ( int j=0; j < be careful here; j++)
{

}

// write out the result
for ( int j=0; j < result.length; j++)
{

}

}
}
```

This version of the program is much easier, but costs more in memory. Usually this is a cost you should be willing to pay. In the very old days of computing, programmers would pick the solution that used the least memory, and often the cost was difficult code.

## Exercise 5 — Panagram Detector

A panagram is a sentence that contains every letter of the alphabet at least once. The most famous panagram, often used in typing tests, is

"The quick brown fox jumps over the lazy dog."

Write a program that prompts the user for a sentence and then says if the sentence is a panagram or not. Declare an array of 25 cells that counts the number of times each letter occurs. Read the entire sentence into a `String` and use `String.charAt()` to scan the letters.

Here are some additional sentences you may wish to test:

• Sphinx of black quartz, judge my vow.
• Pack my box with five dozen liquor jugs.
• Amazingly few discotheques provide jukeboxes.

## Exercise 6 — Smooth Operator

An audio signal is sometimes stored as a list of `int` values. The values represent the intensity of the signal at successive time intervals. Of course, in a program the signal is represented with an array.

Often a small amount of noise is included in the signal. Noise is usually small, momentary changes in the signal level. An example is the "static" that is heard in addition to the signal in AM radio.

Smoothing a signal removes some of the noise and improves the perceptual quality of the signal. This exercise is to smooth the values in an integer array.

Say that the original values are in the array "signal". Compute the smoothed array by doing this: Each value `smooth[N]` is the average of three values: `signal[N-1]`, `signal[N]`, and `signal[N+1]`.

For the first element of `smooth`, average the first two elements of `signal.` For the last element of `smooth`, average the last two elements of `signal.`

Use integer arithmetic for this so that the values in `smooth` are integers.

```import java.io.* ;

class Smooth
{

public static void main ( String[] args )
{
int[] signal  = {5, 5, 4, 5, 6, 6, 7, 6, 5, 4, 1, 4};
int[] smooth

// compute the smoothed value for each
//  cell of the array smooth
smooth  =
smooth[ signal.length-1 ] =
for (  )
{

}

// write out the input
for ( int j=0; j < smooth.length; j++)
{

}

// write out the result
for ( int j=0; j < smooth.length; j++)
{

}

}
}
```

In interpreting the results, remember that integer division discards the remainder. It does not compute a rounded value. Here is a sample run of the program:

```C:\>java Smooth
signal: 1 5 4 5 7 6 8 6 5 4 5 4
smooth: 3 3 4 5 6 7 6 6 5 4 4 4
C:\>
```

## Exercise 7 — Data Tweaker

Say that you are interested in computing the average acid level of coffee as served by coffee shops in your home town. You visit many coffee shops and dip your pH meter into samples of coffee. You record your results in a text file such as the following. The first line of the file gives the number of values that follow.

```13
5.6
6.2
6.0
5.5
5.7
6.1
7.4
5.5
5.5
6.3
6.4
4.0
6.9
```

Unfortunately, your pH meter sometimes produces false readings. So you decide to disregard the reading that is most distant from the average.

Create a text file containing the above or similar data. Now write a program that reads the data into an array (use input redirection). Compute the average of all the data. Now scan through the array to find the value that is farthest (in either direction) from that average. Remember the index of this value, and now scan through the array again, computing an average that does not include this value. Print the new average.

Here is a run of the program:

```C:\>java CoffeeAverage < CoffeeData.txt
data[ 0 ] = 5.6
data[ 1 ] = 6.2
data[ 2 ] = 6.0
data[ 3 ] = 5.5
data[ 4 ] = 5.7
data[ 5 ] = 6.1
data[ 6 ] = 7.4
data[ 7 ] = 5.5
data[ 8 ] = 5.5
data[ 9 ] = 6.3
data[ 10 ] = 6.4
data[ 11 ] = 4.0
data[ 12 ] = 6.9
average: 5.930769230769231
most distant value: 4.0
new average: 6.091666666666668
```

## Exercise 8 — Further Tweaking

Your pH meter has become much less reliable (ever since you dropped it on the floor due to uncontrollable shaking after ten cups of coffee). You decide to compute several averages from your data:

• The average of all values. (Call this average A1.)
• The average of all values, excluding the one furthest from A1. (Call this average A2.)
• The average of all values, excluding the two furthest from A2. (Call this average A3.)
• The average of all values, excluding the three furthest from A3.

Write a program that computes these averages for the above or similar data.

## Exercise 8 —Tweakers Delight

You have a couple of double espressos, your brain has started quivering, and you notice that with an array of N values you can compute N averages:

• The average of all values. (Call this average A1.)
• The average of all values, excluding the one furthest from A1. (Call this average A2.)
• The average of all values, excluding the two furthest from A2. (Call this average A3.)
• The average of all values, excluding the three furthest from A3.
• . . .
• The average of all values, excluding the N-1 furthest from A(N-1). (This is the average of just one element; in other words, the value of the element closest in value to A1.)

Write a program that computes these averages and prints them out.

## Exercise 9 — Array Equality

Write your own `equals( int[], int[] )` method.

```import java.util.Arrays;

class ArrayEquality
{
public static boolean myEquals( int[] a, int[] b )
{
}

public static void main ( String[] args )
{
int[] arrayA = { 1, 2, 3, 4 };
int[] arrayB = { 1, 2, 3, 4 };

System.out.print("Arrays says: ")    ;
if ( Arrays.equals( arrayE, null ) )
System.out.println( "Equal" );
else
System.out.println( "NOT Equal" );

System.out.print("myEquals says: ")    ;
if ( Arrays.equals( arrayE, null ) )
System.out.println( "Equal" );
else
System.out.println( "NOT Equal" );
}
}
```

Check that your method agrees with the `Arrays` method. Pay attention to `null` arguments and arrays of one element.

## Exercise 10 — Arrays with Same Elements

Write a method that detects if two integer arrays contain the same elements, but not necessarily int the same order: `sameElts( int[], int[] )` method.

The method should not change the arrays it is given as parameters. The position of elements in the array might be crucial to an application. In general, methods should avoid side effects. So i`main()` (below) the two arrays should not change.

```class ArraySameElements
{
public static boolean sameElts( int[] a, int[] b )
{
}

public static void main ( String[] args )
{
int[] arrayA = { 1, 2, 3, 4, 2 };
int[] arrayB = { 4, 2, 3, 2, 1 };

if ( sameElts( arrayE, null ) )
System.out.println( "Same Elements" );
else
System.out.println( "DIFFERENT elements" );

}
}
```

"Same elements" means both arrays have the same length and each has the same number of the same value, but not necessarily in the same locations. The arrays may have more than one of the same element. Declaring a third and perhaps a fourth array inside the method might be helpful.

First Approach (easy): use one of the `sort()` methods in class `Array` and then use `equals()`. (But be careful not to change the arrays in `main()`.)

Second Approach (harder): Assume that the two arrays have elements in a limited range, perhaps zero to one hundred. Declare two local arrays indexed zero to one hundred that count how many of each value is in each array.

Third Approach (hard): Declare a local array of boolean called `used` regarded as a "shadow" of the second parameter, `b`. Initialize each cell of `used` to `false`. `used[j]` is set to `true` when the value in `a` is found in `b[j]`. Now scan through `a` updating `used` for each element.

For each `a[k]`, find that value somewhere in `b` (say at `b[j]`) and set `used[j]` to `true`. If `used[j]` is already `true` continue searching. If the value is not found, immediately return `false`.

## Exercise 9 — Integer with No Repeated Digits

Some integers are written (in base 10) with no repeated digits. For example, 123 does not repeat any digits, but 144 does repeat a digit. Other examples are 8134 (no repeats) and 90129 (repeats).

Write a method that determines if its parameter contains repeated digits. Assume that the integer is positive.

```static boolean repeatedDigits( long val )
```

To determine the digits of `val`, use the `%` operator to get the right-most digit and divide by 10. (There is no need to convert to a `String`.) Test your method in a `main()` that asks the user for numbers to test.

## Exercise 10 — Squares with No Repeated Digits

Write a program that produces a list of squares that contain no repeated digits. For example 52 == 25 works. 102 == 100 does not.

Write `main()` so that it asks the user for how many digits the integers it tests contain. So if the user enters 5, all 5-digit integers with non-repeated digits are printed.

Are there any 10-digit squares that contain each digit only once?

Write a `main()` that searches for all such integers up to a limit. Are there any integers whose square and cube together use each of the 10 digits only once each?