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

用到了全排列的方法
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;
			   }
		  }	
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值