ppatel.it20
BAN USERHere is my solution. easy to understand.
public class GenerateMatrixWithNoSameTypeofElement {
public static void main(String[] args){
int a[][] = generateMatrix(4);
for(int i = 0; i<4; i++ ){
for(int j =0; j<4; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
// System.out.println(validMatrix(a));
}
private static int[][] generateMatrix(int p) {
int a[][] = new int[p][p];
int i=0,j;
while(i<p){
j=0;
while(j<p){
Random rand = new Random();
boolean lop = true;
int x = rand.nextInt(p);
while(lop && (j >=2 || i >=2)){
if(j>=2){
if(x == a[i][j-1] && x == a[i][j-2]){
x = rand.nextInt(p);
lop = true;
}
else
lop = false;
}
if(i>=2){
if(x == a[i-1][j] && x == a[i-2][j]){
x = rand.nextInt(p);
lop = true;
}
else{
lop = false;
}
}
}
a[i][j] = x;
j++;
}
i++;
}
return a;
}
Here is my solution.
- ppatel.it20 January 04, 2017