Question 2 (25 points)
Complete
the definition of method Cellular below. Sample output might be:
1
1 0 1 0 0 1
0
1 1 0 0 0 1
1
1 1 0 1 0 0
1
0 1 1 0 0 0
etc.
// Given the initial state of
a 1-D cellular automaton A containing
// just 0's and 1's, simulate
A indefinitely according to the rule:
// Each cell remains unchanged
unless its two neighbors are equal,
// in which case the cell
changes to the opposite binary value (i.e.,
// 0->1, 1->0 ).
// Note that A[ 0 ] and A[
A.length - 1 ] are considered neighbors.
Output
// the initial state of A, and
all subsequent states.
static void Cellular( int[] A )
{
int n =
A.length;
int[] B = new int[ n ];
while ( true )
{
for( int i = 0; i < n; i ++ )
{
System.out.print(
A[ i ] + " " );
if ( A[ (n
- 1 + i)%n ] == A[ (i + 1)% n ] )
B[ i ] = ( A[ i ] + 1 )%2;
else
B[ i ] = A[ i ];
}
System.out.println();
A = B;
B = new int[ n ];
}
}
Comments
A
careful construction can make work easy.
The easiest solution comes from using the modulo function to inspect
nearest neighbors; without using the function, more care is required to
identify and correctly handle the end cases.
This approach not only takes up valuable examination time, but is far
more prone to error. Students who
avoided modular arithmetic should study the solution as it avoids the necessity
of having to consider cases. Note too
how modular arithmetic was again used to add a briskness to the solution by
cleverly "flipping" the value of B without the use of an if-else construct.