1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
import java.util.Random;
import org.junit.Test;
public class RandomIntMatrix {
protected int size ;
protected int[] content ;
public RandomIntMatrix() {
// for JUnit to be quiet...
}
public RandomIntMatrix(int inSize) {
this.size = inSize ;
this.content = new int[inSize * inSize] ;
shuffle() ;
}
public void shuffle() {
int s2 = this.size * this.size ;
Random r = new Random();
int start = r.nextInt(s2) ;
int value = 1 ;
for(int i=start;i<s2;i++, value++)
this.content[i] = value ;
for(int i=0;i<start;i++, value++)
this.content[i] = value ;
for(int i=0;i<s2/2;i++) {
int i1 = r.nextInt(s2) ;
int i2 = r.nextInt(s2) ;
int t = this.content[i1] ; this.content[i1] = this.content[i2] ; this.content[i2] = t ;
}
}
public int get(int row, int col) {
return this.content[ (row * this.size) + col ] ;
}
public void set(int row, int col, int value) {
this.content[(row * this.size) + col] = value ;
}
private final int SizeToTest = 10 ;
private final int TimesToTest = 2 ;
@Test
public final void testMatrix() {
RandomIntMatrix m = new RandomIntMatrix(SizeToTest) ;
for(int k=0;k<TimesToTest;k++) {
for(int i=0;i<SizeToTest;i++) {
for(int j=0;j<SizeToTest;j++)
System.out.print(m.get(i, j) + "\t") ;
System.out.println();
}
System.out.println();
m.shuffle();
}
}
} |
Partager