---
title: "计算24点"
author: "cjf068"
date: "2012-03-13T21:49:03Z"
tags: []
categories: ["编程语言"]
slug: "24"
draft: false
lastmod: "2012-03-13T21:49:03Z"
id: 1452744
url: "https://cjf068.iteye.com/blog/1452744"
---

\[code="java"]\[/code]计算n个数的全排列 \[code="java"] package org.jf.alg.stack; import java.util.List; import java.util.ArrayList; public class PermUtil { /\** * @param args \*/ public static void main(String\[] args) { List list = perm(new String\[]{"a","b","c","d"},0,4,null); List source = new ArrayList(); String ss \[] = list.get(0); for(String s:ss) { source.add(s); } List&gt; container = new ArrayList&gt;(); System.out.println(container.size()); // for(String\[] ss:list) // { // printArray(ss); // } System.out.println(list.size()); } /\** * * void perm (char \*a, const int k，const int n) { // n 是数组a的元素个数，生成a\[k],…,a\[n-1]的全排列 int i; if (k = = n-1) { // 终止条件，输出排列 for ( i=0; i perm(String \[]s,int k,int n,List result) { List result1= result; if (k == n-1) { String ss \[] = new String\[s.length]; for( int i = 0;i&lt;=n-1; i++) { ss\[i] = s\[i]; } if(result1==null) result1 = new ArrayList(); result1.add(ss); }else { for(int i = k;i toPostfixExp(String middleFixString,boolean fraction) { Stack opSt = new Stack(); List postExpList = new ArrayList(); List eleList = getElementList(middleFixString,fraction); for(String ele:eleList) { char c = ele.charAt(0); if(ele.length()==1 && !(c&gt;='0' && c&lt;='9')) { switch(c) { case '(' : opSt.push(ele); break ; case ')' : for(;;) { if(opSt.isEmpty()) break; String op = opSt.pop(); if(op .equals("(")) break; postExpList.add(op); } break ; default: if(opSt.isEmpty()) opSt.push(ele); else {//比较优先级 while(!opSt.isEmpty()) { char opTop = opSt.peek().charAt(0); if(opSt.isEmpty()||opTop == '(') { opSt.push(ele); break; } if(getPriority(c)&gt;getPriority(opTop)) { opSt.push(ele); break; } else { postExpList.add(opSt.pop()); opSt.push(ele); break; } } } } } else { postExpList.add(ele); } } while(!opSt.isEmpty()) { postExpList.add(opSt.pop()); } return postExpList; } private static List getElementList(String middleFixExp,boolean fraction) { List list = new ArrayList(); char \[] seprator = null; if(fraction) seprator = new char\[]{'+','-','\*','(',')'}; else seprator = new char\[]{'+','-','/','\*','(',')'}; int opBeginIndx = -1; boolean isOperator = false; for(int i=0;i sta = new Stack(); List list = toPostfixExp(exp,fraction); String s =""; while(list.size()&gt;0) { s = list.remove(0); if(s.length()==1 && !(s.charAt(0)&gt;='0'&&s.charAt(0)&lt;='9')) { String y = sta.pop(); String x = sta.pop(); if("+-\*/".indexOf(s)&gt;=0) { String result = ""; if(fraction) result =caculateFraction(x,y,s.charAt(0)); else result =caculateInteger(x,y,s.charAt(0)); sta.push(result); } else throw new RuntimeException("not support operator:"+s); } else { sta.push(s); } } return sta.pop(); } public static String evaluate(List postfix\_exp,boolean fraction) throws Exception { Stack sta = new Stack(); String s =""; while(postfix\_exp.size()&gt;0) { s = postfix\_exp.remove(0); if(s.length()==1 && !(s.charAt(0)&gt;='0'&&s.charAt(0)&lt;='9')) { String y = sta.pop(); String x = sta.pop(); if("+-\*/".indexOf(s)&gt;=0) { String result = ""; if(fraction) result =caculateFraction(x,y,s.charAt(0)); else result =caculateInteger(x,y,s.charAt(0)); sta.push(result); } else throw new RuntimeException("not support operator:"+s); } else { sta.push(s); } } return sta.pop(); } private static String caculateInteger(String x,String y,char operator)throws Exception { int px = Integer.parseInt(x); int py = Integer.parseInt(y); int result = 0; switch(operator) { case '+': result = px + py; break; case '-' : result = px - py ; break; case '\*' : result = px * py; break; case '/' : result = px / py; break; } return result+""; } private static String caculateFraction(String x,String y,char operator) { int dx = 1, dy = 1,nx = 1, ny = 1; if(x.indexOf("/")&gt;0) { dx = Integer.parseInt(x.substring(x.indexOf("/")+1)); nx = Integer.parseInt(x.substring(0,x.indexOf("/"))); }else { nx = Integer.parseInt(x); } if(y.indexOf("/")&gt;0) { dy = Integer.parseInt(y.substring(y.indexOf("/")+1)); ny = Integer.parseInt(y.substring(0,y.indexOf("/"))); }else { ny = Integer.parseInt(y); } String s = ""; int sn = 0; int sd = 1; switch(operator) { case '+': sn = nx\*dy+ny\*dx; sd = dx\*dy; break; case '-': sn = nx\*dy-ny\*dx; sd = dx\*dy; if(sn%sd==0) s = (sn/sd)+""; else s = sn+"/"+sd; break; case '\*': sn = nx\*ny; sd = dx\*dy; break; case '/': sn = nx\*dy; sd = ny\*dx; break; } if(sn%sd==0) s = (sn/sd)+""; else s = sn+"/"+sd; return s; } private static int getPriority(char operator) { switch(operator) { case '+': return 0; case '-': return 0; case '\*' : return 1; case '/' : return 1; case '%' : return 1; default : return -1; } } /\** * * @param source 操作数集合 * @return \*/ public static List&gt; getAllPostfixExp(List source) { List&gt; container = new ArrayList&gt;(); Stack st = new Stack(); st.push(source.get(0)); fn2(source,1,true,source.size()-1,st,container); // fn(source,1,st,container); return container; } /\** * * @param source * @param k * @param st * @param container \*/ private static void fn(List source,int k,Stack st,List&gt; container) { if(container == null) throw new RuntimeException("container is null"); String \[]operators = new String\[]{"+","-","/","\*"}; if(k&gt;=source.size()) return; st.push(source.get(k)); for(String op:operators) { st.push(op); if(k==source.size()-1) { List sta = new ArrayList(); sta.addAll(st); container.add(sta); }else { fn(source,k+1,st,container); } st.pop(); } st.pop(); } /\** * * @param source * @param k 当前插入序号 * @param st * @param rest\_operator\_num 还剩几个操作符没有插入 * @param container \*/ private static void fn2(List source,int k,boolean push, int rest\_operator\_num,Stack st,List&gt; container) { if(container == null) throw new RuntimeException("container is null"); String \[]operators = new String\[]{"+","-","/","\*"}; if(k&gt;=source.size()) return; if(push) st.push(source.get(k)); //本次最多能插入的操作符个数 int max\_num = rest\_operator\_num-(source.size()-1-k); if(k == source.size()-1)//将剩余的所有操作符推入 { for(int j=0;j sta = new ArrayList(); if(st.size()==source.size()\*2-1)//有一bug 计算出来的表达式比实际的多 尚未找到bug出在哪里 尚且在此判断 去除不合法的表达式 { sta.addAll(st); container.add(sta); } }else { fn2(source,k,false,max\_num-j-1,st,container);//? } st.pop(); } } }else { for(int i=0;i&lt;=max\_num;i++) { if(i!=0)//push i 个操作符 pushOperator(i,source,k,false,rest\_operator\_num-i,st,container); else if(i ==0) { fn2(source,k+1,true,rest\_operator\_num,st,container); } } } if(push) st.pop(); } private static void pushOperator(int num, List source,int k,boolean push, int rest\_operator\_num,Stack st,List&gt; container) { String \[]operators = new String\[]{"+","-","/","\*"}; if(num&lt;1) return; for(String op:operators) { st.push(op); if(num == 1) { fn2(source,k+1,true,rest\_operator\_num,st,container); } else { pushOperator(num-1,source,k,push,rest\_operator\_num,st,container); } st.pop(); } } public static void main(String args\[]) { // System.out.println(Integer.parseInt("4/5")); List source = new ArrayList(); source.add("2"); source.add("2"); source.add("4"); source.add("8"); // List&gt; container = getAllPostfixExp(source); // System.out.println(container.size()); // String s ="+"; // System.out.println(s.length()==0 && !(s.charAt(0)&gt;='0'&&s.charAt(0)&lt;='9')); // List list = toPostfixExp("12+((3\*(2-4/5))+5)\*3",true); // System.out.println(OperationUtil.evaluate("3+2-9/4", true)); // List&gt; all = getAllPostfixExp(source); // for(int i=0;i list = PermUtil.perm(ops, 0, ops.length, null); for(String ss\[]:list) { List list1 = new ArrayList(); for(String s:ss) { list1.add(s); } List&gt; expList = getAllPostfixExp(list1); // System.out.println("exp list size = "+expList.size()); for(List exp:expList) { StringBuffer sbu = new StringBuffer(); for(String str:exp) { sbu.append(str).append(" "); } // System.out.println(sbu.toString()); String result = ""; try { result = evaluate(exp,true); } catch (Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); continue; } if("24".equals(result)) { System.out.println("find success:"+sbu.toString()); // System.out.println(); } } } } static void test8383() { List source = new ArrayList(); source.add("8"); source.add("3"); source.add("8"); source.add("3"); List&gt; all = getAllPostfixExp(source); for(int i=0;i