vendredi 17 mars 2017

generating unique random rows and columns in 2 dimensional array

Using the code below (by user3437460 in a very similar question ), random unique numbers in both rows and columns of a 2D array is perfectly displaying EXCEPT THAT the first row gives the output of ordered/sorted random unique numbers which is not desired!

Based on the comment given by user3437460, testMethods class is flexible and with replacement of Util.shuffle(board[0]); first row will also be shuffled BUT it actually is NOT.

Any help will be greatly appreciated.

class testMainClass
{
 public static void main(String args[])
 {      
    int size = 9;

    int[][] test= new int[size][size];
    test[0] = testMethods.testCreateOrderedArray(size, 1);

    for(int x=1; x<size; x++)
    {          
        test[x] = testMethods.testCreateOrderedArray(size, 1);
        do
        {
            testMethods.testShuffle(test[x]);
        }
        while(!testMethods.testCompare2DArray(test[x], test, 0, x));        
    }       
    testMethods.testPrint(test);  
  }
}

final class testMethods
{
    public static void testShuffle(int[] num)
    {
    Random rnd = new Random();
    for(int x=0; x<num.length; x++)
        testSwap(num, x, rnd.nextInt(num.length));
    }

    public static void testSwap(int[] num, int a, int b)
    {
    int temp = num[a];
    num[a] = num[b];
    num[b] = temp;
    }

    public static int[] testCreateOrderedArray(int size, int startValue)
    {
    int[] num = new int[size];
    for(int x=0; x<num.length; x++)
        num[x] = x+startValue;      
    return num;
    }


    public static boolean testCompare2DArray(int[] num1, int[][] num2, int   start, int end)
    {
    for(int x=start; x<end; x++)
        if(!testCompareArray(num1, num2[x]))
            return false;
    return true;        
    }


    public static boolean testCompareArray(int[] num1, int[] num2)
    {
     if(num1.length != num2.length)
        return false;
     for(int x=0; x<num1.length; x++)
        if(num1[x] == num2[x])
            return false;
     return true;        
    }

    public static void testPrint(int[][] num)
    {
     for(int x=0; x<num.length; x++)
     {
        for(int y=0; y<num[0].length; y++)
            System.out.print(num[x][y] + " ");
        System.out.println(""); 
     }                           
    }
}




Aucun commentaire:

Enregistrer un commentaire