|
|
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
These tips and cautions will help you write better programs and save you from agonizing over why the compiler produces error messages.
null to a link field. Don't ignore those null assignments in your source code; their absence reduces your code's clarity.
if (limit == 1) return 1;). Otherwise, the recursion will continue until the method-call stack overflows.
Last month, I presented you with three exercises. Here are my answers.
The binary-search algorithm as a flowchart. Click on thumbnail to view full-size image.">![]()
The binary-search algorithm as a flowchart. Click on thumbnail to view full-size image.
n x n matrix of integers from 1 to n2, such that the sum is the same for every row, column, and diagonal. If n equals 5, for example, we end up with the following matrix (where the common sum is 65):========================== | 15 | 8 | 1 | 24 | 17 | |------------------------| | 16 | 14 | 7 | 5 | 23 | |------------------------| | 22 | 20 | 13 | 6 | 4 | |------------------------| | 3 | 21 | 19 | 12 | 10 | |------------------------| | 9 | 2 | 25 | 18 | 11 | ==========================
A simple algorithm for generating a magic square when n is odd:
Express the algorithm above in pseudocode and as a Java application for any odd n.
Below is the source code to a Java application that implements the algorithm above:
// MagicSquare.java
class MagicSquare
{
final static int N = 5; // N must be odd
static int [][] square;
static
{
// Terminate the program if N is even. Determine "evenness" by
// checking if the least-significant bit is 0. If so, N is even.
if ((N & 1) == 0)
{
System.out.println ("Error: N is even.");
System.exit (0);
}
// Create an N x N matrix to hold the magic square.
square = new int [N][];
for (int i = 0; i < N; i++)
square [i] = new int [N];
}
public static void main (String [] args)
{
// Store 1 in the middle of the first row.
square [0][(N - 1) / 2] = 1;
// key contains the next value to store. (i, j) contains the
// current (row, column) position.
int key = 2, i = 0, j = (N - 1) / 2;
// Continue to build the magic square.
while (key <= N * N)
{
int k = i - 1; // Look up.
if (k < 0)
k += N;
int l = j - 1; // Look to the left.
if (l < 0)
l += N;
if (square [k][l] != 0)
i = (i + 1) % N; // Move down if square is occupied.
else
{
i = k; // square [k][l] needs to be assigned.
j = l;
}
square [i][j] = key; // Assign value to square.
key++; // Obtain next value to store.
}
// Output magic square.
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
System.out.print (square [i][j] + " ");
System.out.println ();
}
}
}
Your pseudocode should express the essential concepts shown in the Java source code.
int [] x = { }; accomplish (assuming that code fragment is legal)?int [] x = { }; creates a zero-length one-dimensional array. In other words, there are no elements.