Question

I am trying to make a program that finds the maximum possible determinant of an n*n binary [0,1] matrix. The problem with my current code is that after 4x4, the numbers are too long for a 'long' to hold. The code below is what I use to generate the matrices.

for (int j = 0; j < Math.pow(2, Math.pow(dim, 2)); j++) { //for each possible matrix
            int[][] matrix = new int[dim][dim];//make a 2d i*i matrix
            long t = Long.valueOf(Long.toBinaryString(j)); //line 58

            //format the string so its length = # of elements in the matrix
            String format = "%0" + (dim * dim) + "d";
            String s = String.format(format, t);

            //fill matrix
            int counter = 0;
            for (int k = 0; k < dim; k++) {//for each row
                for (int l = 0; l < dim; l++) {//for each column
                    matrix[k][l] = s.charAt(counter) - 48; //the -48 is for ascii conversions
                    counter++;
                }// end l
            }// end k -- matrix is filled

The error I get when I go over a 4*4:

     Exception in thread "main" java.lang.NumberFormatException: For input string: "10000000000000000000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:444)
at java.lang.Long.valueOf(Long.java:540)
at determinants.Determinants.findMaxBinDet(Determinants.java:58)
at determinants.Determinants.main(Determinants.java:38)

What else can I do to parse the number into binary?

Was it helpful?

Solution

It appears you want to create with all the combinations of 0 and 1 in the cells. A much simpler approach is

for (long j = 0, limit = 1<<(dim*dim); j < limit; j++) { //for each possible matrix
    int[][] matrix = new int[dim][dim];//make a 2d i*i matrix

    //fill matrix
    for (int k = 0, counter = 0; k < dim; k++) {//for each row
        for (int l = 0; l < dim; l++, counter++) {//for each column
            matrix[k][l] = (j >>> counter) & 1;
        }
    }

This will only work up to 7x7 matrixes but since generating all 8x8 combination is like to take more than a lifetime, you need another approach for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top