您的位置:首页 > 其它

全国软件大赛(猜算式)全排列实现

2013-04-23 21:38 225 查看
用到了全排列的方法
package com.lanqiaobei.dati_01;

import java.util.Arrays;
import java.util.*;

public class GetchengJi {

/*
* 看下面的算式:

□□ x □□ = □□ x □□□

它表示:两个两位数相乘等于一个两位数乘以一个三位数。

如果没有限定条件,这样的例子很多。

但目前的限定是:这9个方块,表示1~9的9个数字,不包含0。
该算式中1至9的每个数字出现且只出现一次!

比如:
46 x 79 = 23 x 158
54 x 69 = 27 x 138
54 x 93 = 27 x 186
.....

请编程,输出所有可能的情况!

注意:
左边的两个乘数交换算同一方案,不要重复输出!
不同方案的输出顺序不重要

*
* */

/**
* @param args
* @author lixingle
*/
public static StringBuffer sb=new StringBuffer();
public static HashSet<String> hs=new HashSet<String>();		//用于存放结果字符串等式

public static void main(String[] args) {
getResult();

//遍历HashSet<String> hs
Iterator i = hs.iterator();
while(i.hasNext()){
String temp = (String)i.next();
System.out.println(temp);
}
}
public static void getResult(){
char c[] = { '1', '2', '3' ,'4','5', '6', '7' ,'8','9'};// 声明一个字符型数组
sort(c, 0, c.length - 1);// 调用函数,进行全排列  把结果存在StringBUffer中
int ch;
String str=sb.toString();
int count=0;
while(count<str.length()){		//循环取出几个乘数
int a=Integer.valueOf((str.substring(count, count+=2)));
int b=Integer.valueOf((str.substring(count, count+=2)));
int n=Integer.valueOf((str.substring(count, count+=2)));
int m=Integer.valueOf((str.substring(count, count+=3)));
if (a*b==n*m){
if (a>b){
ch=a;a=b;b=ch;
}
String stl=String.format(a+"*"+b+"="+n+"*"+m);
hs.add(stl);
}
count+=1;			//跳过回车换行
}

}
//定义全排列函数
public static void sort(char[] c, int begin, int end) {
if (begin == end) {// 如果begin等于end说明,数组中的元素交换完毕,可以进行打印输出
sb.append(String.valueOf(c)+"\n");	   //吧全排列结果存在sb中
} else {// 如果元素还没有交换完毕,继续进行递归
for (int i = begin; i <= end; i++) {
char temp = c[begin];// 将首元素与其后的第i个元素进行交换
c[begin] =c[i];
c[i]= temp;
// 递归循环调用
sort(c, begin + 1, end);
// 还原数组
c [i]= c[begin];
c[begin] = temp;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: