In: Computer Science
Randomly generate 0, 1, or 2 in a 100 by 100 2d array.
For each entry in the 2d array, count the number of 0’s and 1’s in
the surrounding entries.
Save the result in two 2d arrays: one for the number of 0’s, one
for the number of 1’s.
For example:
0 0 1
2 1 0
0 0 0
The number of 0’s for a[0][0] is 1; the number of 1’s for
a[0][0] is 1;
The number of 0’s for a[0][1] is 2; the number of 1’s for a[0][1]
is 2;
The number of 0’s for a[0][2] is 2; the number of 1’s for a[0][2]
is 1;
The number of 0’s for a[1][0] is 4; the number of 1’s for a[1][0]
is 1;
The number of 0’s for a[1][1] is 6; the number of 1’s for a[1][1]
is 1;
The number of 0’s for a[1][2] is 3; the number of 1’s for a[1][2]
is 2;
The number of 0’s for a[2][0] is 1; the number of 1’s for a[2][0]
is 1;
The number of 0’s for a[2][1] is 3; the number of 1’s for a[2][1]
is 1;
The number of 0’s for a[2][2] is 2; the number of 1’s for a[2][2]
is 1;
NOTE: Since no language was mentioned I have made this program in Java. To make the program execution easy and output understandable I have taken a 3 by 3 marix. For 100 by 100 matrix just replace the initial values of n1 and n2 by 100.
import java.util.Random;
class Randomly
{
public static void main(String[]args)
{
int a[]={0,1,2};// array for selecting random numbers for our matrix
int n1, n2;// variables for number of rows and columns of our matrix
n1=3;
n2=3;
int b[][]=new int[n1][n2];// initializing our matrix
int i, k, j, c1, c2;
Random r=new Random();
for(i=0; i<n1; i++)
{
for(j=0; j<n2; j++)
{
k=r.nextInt(a.length);// assigning random numbers in the matrix
b[i][j]=k;
}
}
for(i=0; i<n1; i++)// nested loops to print the matrix
{
for(j=0; j<n2; j++)
{
System.out.print(b[i][j]+" ");
}
System.out.println();
}
for(i=0; i<n1; i++)// nested loops to count the number of 1's and 0's surrounding an element
{// first we are checking whether an index is available or not before checking for 1's and 0's
for(j=0; j<n2; j++)
{c1=0; c2=0;
if(j-1>=0)
{
if(b[i][j-1]==1)
c1++;
if(b[i][j-1]==0)
c2++;
}
if(i-1>=0&&j-1>=0)
{
if(b[i-1][j-1]==1)
c1++;
if(b[i-1][j-1]==0)
c2++;
}
if(i-1>=0)
{
if(b[i-1][j]==1)
c1++;
if(b[i-1][j]==0)
c2++;
}
if(i-1>=0&&j+1<n2)
{
if(b[i-1][j+1]==1)
c1++;
if(b[i-1][j+1]==0)
c2++;
}
if(j+1<n2)
{
if(b[i][j+1]==1)
c1++;
if(b[i][j+1]==0)
c2++;
}
if(i+1<n1&&j+1<n2)
{
if(b[i+1][j+1]==1)
c1++;
if(b[i+1][j+1]==0)
c2++;
}
if(i+1<n1)
{
if(b[i+1][j]==1)
c1++;
if(b[i+1][j]==0)
c2++;
}
if(i+1<n1&&j-1>=0)
{
if(b[i+1][j-1]==1)
c1++;
if(b[i+1][j-1]==0)
c2++;
}
System.out.println("The number of 0's for a["+i+"]"+"["+j+"]"+" is "+c2+" ; the number of 1's for a["+i+"]"+"["+j+"]"+" is "+c1+" ;");
}
}
}//end of main method
}// end of class