
由题已知这是一个匹配题目,题目已经说了三阶幻方是给定的,经过镜像和旋转,镜像*2旋转*4;
总共八种方案,然后接收每次的数据去匹配(跳过0),如果匹配就输出匹配的数组,如果不匹配就输出-1。

题目给出了:492357816 旋转和镜像可以得到"672159834", "276951438", "294753618", "834159672", "438951276", "618753294", "816357492"
①存储8个固定字符串
②以字符串的形式接收给定数组
③进行比对,若为0则跳过,若不对应记录0,若对应记录下标
④输出结果,没找到ToMany;找到输出对应下标字符串
代码如下👇
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String[] s1= {
"672159834", "276951438", "294753618","492357816",
"834159672", "438951276", "618753294", "816357492"
};
String s2="";
for (int i = 0; i < 3; i++) {
s2+=scan.nextLine();
}
s2=s2.replaceAll(" ", "");
System.out.println(s2);//测试点
int count=0;
//System.out.println(s2.charAt(1)!='0' && s1[0].charAt(1)==s2.charAt(1));测试
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < 9; j++) {
if (s2.charAt(j)!='0' && s1[i].charAt(j)==s2.charAt(j)) {
count++;
}
if (s2.charAt(j)!='0' && s1[i].charAt(j)!=s2.charAt(j)) {
count=0;
break;
}
}
if (count>0) {
count=i;
break;
}
}
if (count==0) {//本来判断赋值为-1.这里省略
System.out.println("Too Many");
}else {
for (int i = 0; i < 9; i++) {
System.out.print(s1[count].charAt(i)+" ");
if (i==2) {
System.out.println();
}
if (i==5) {
System.out.println();
}
if (i==8) {
System.out.println();
}
}
}
scan.close();
}
进行优化👇
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String[] s1= {
"672159834", "276951438", "294753618","492357816",
"834159672", "438951276", "618753294", "816357492"
};
String s2="";
for (int i = 0; i < 3; i++) {
s2+=scan.nextLine();
}
s2=s2.replaceAll(" ", "");
int count=-1;//寄存下标或答案
for (int i = 0; i < 8; i++) {
if (compares(s2, s1[i])) {//比较成功进行赋值
count=i;
break;
}
}
if (count==-1) {//比较失败输出 太多
System.out.println("Too Many");
}else {
prints(s1, count);
}
scan.close();
}
public static boolean compares(String s1,String s2) {//比较
for (int i = 0; i < 9; i++) {
if (s1.charAt(i)!='0') {
if (s1.charAt(i)!=s2.charAt(i)) {
return false;
}
}
}
return true;
}
public static void prints(String[] s,int x) {//打印
for (int i = 0; i < 9; i++) {
System.out.print(s[x].charAt(i)+" ");
if (i==2) {
System.out.println();
}
if (i==5) {
System.out.println();
}
if (i==8) {
System.out.println();
}
}
}