package cn.edu.csu;
/**
* 此算法的主要思想是以第一行的数为基础,让这九个互异数轮转,即若第一排是 123456789,则第二排是912345678,
* 依此类推,也就是把最后一个数移到第一个,其它的顺着后移,这样不论是行还是列得到的都是互异的数字了,这样
* 就得到了一组符合要求的数据。又由于第一行共有 9!种排法,所以共有 9!组符合要求的排法。
* 此外,编程时把数字的相关操作转化了字符串来实现,因为String的方法比较多,且操作方便,大大
* 简化了了编程。
* @author minbing
*
*/
public class OtherGrid {
/**
* @param args
*/
public String[] creatDifString(){
int k1, k2, k3, k4, k5, k6, k7, k8, k9;
String[] str = new String[362880];
int i = 0;
for(k1 = 1; k1 <= 9; k1++){
for(k2 =1; k2 <= 9; k2++){
if(k2 ==k1){
continue;
}
for(k3 = 1; k3 <= 9; k3++){
if(k3 ==k1 ||k3 ==k2){
continue;
}
for(k4 = 1; k4 <=9; k4++){
if(k4 == k1 ||k4 ==k2 ||k4==k3){
continue;
}
for(k5 = 1; k5 <=9; k5++){
if(k5 == k1 ||k5 == k2 ||k5 ==k3 ||k5 ==k4){
continue;
}
for(k6 = 1; k6<=9; k6++){
if(k6 == k1 || k6 == k2 || k6 ==k3 ||k6 ==k4 ||k6 ==k5){
continue;
}
for(k7 = 1; k7 <=9; k7++){
if(k7 ==k1 || k7 == k2 || k7 == k3 || k7 ==k4 || k7 ==k5 ||k7 == k6){
continue;
}
for(k8 = 1; k8 <= 9; k8++){
if(k8 == k1 ||k8 ==k2 || k8 == k3 ||k8 ==k4 ||
k8 == k5 || k8 == k6 || k8 == k7){
continue;
}
for(k9 = 1; k9 <= 9; k9++){
if(k9 == k1 || k9 == k2 || k9 == k3 || k9 == k4 ||
k9 == k5 || k9 == k6 || k9 == k7 || k9 == k8){
continue;
}
str[i] = String.valueOf(k1) + String.valueOf(k2) + String.valueOf(k3) +
String.valueOf(k4) + String.valueOf(k5) + String.valueOf(k6) +
String.valueOf(k7) + String.valueOf(k8) + String.valueOf(k9);
i++;
}
}
}
}
}
}
}
}
}
return str;
}
/**
* 把最后一个字符移到第一个,实现轮转
* @param str
* @return
*/
public String printdif(String str){
int str_len = str.length();
int m = 0;
str = str.charAt(str_len – 1) + str.substring(0, str_len – 1);
return str;
}
public static void main(String[] args) {
String[] str = new OtherGrid().creatDifString();
int N = 326880, len = 9;
String str1 = null;
for(int i = 0; i < N; i++){
int m = 0;
int n = i + 1;
str1 = str[i];
System.out.println(“以下是第” + n + “组符合要求的数据”);
while(m < len){
System.out.println(str1);
str1 = new OtherGrid().printdif(str1);
m++;
}
}
}
}