mardi 3 mars 2015

char array to 2d char array with constraints



I need help with sorting elements of the char[] {'A','B','C','D',' ',' '} into a char[6][6] where each row and each column has each of the 6 char[6] elements once. Below is the code I have so far. The problem is that I cannot generate a 2d array that fits this description. If anyone knows how to do this, that would be great!


Example ending array (I need a program that will generate ALL permutations, not just this one.):



ABCD
ABCD
ABCD
D ABC
CD AB
BCD A


My code:



import java.util.Arrays;
import java.util.Collections;

public class Main {
public static char[] characters = {'A','B','C','D',' ',' '};

public static void main(String[]a){
char[][] temp = new char[6][];
temp = getRows(characters);
}

public static char[][] getRows(char[] chars){
char[][] rows = new char[6][];
int a = 0;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
for (int k = 0; k < 6; k++) {
for (int l = 0; l < 6; l++) {
for (int m = 0; m < 6; m++) {
tester:
for (int n = 0; n < 6; n++) {
char[] temp = {chars[i], chars[j], chars[k], chars[l], chars[m], chars[n]};
for (int o = 0; o < 6; o++) {
//System.out.println(arrayToString(temp));
if (Collections.frequency(Arrays.asList(temp), characters[o]) > 1 || Collections.frequency(Arrays.asList(temp), characters[o]) == 0) {
continue tester;
}
}
if (a + 1 == 6) return rows;
System.out.println(arrayToString(temp));
rows[a] = temp;
a++;

}
}
}
}
}
}
return new char[6][6];
}

public static String arrayToString(char[] objects) {
String s = "{";
for (int i = 0; i < objects.length; i++) {
s += objects[i];
if (i < objects.length - 1)
s += ",";
}
s += "}";
return s;
}

}



Aucun commentaire:

Enregistrer un commentaire