當前位置:首頁 » 編程語言 » java24點

java24點

發布時間: 2022-08-20 05:21:24

A. java程序設計:算24點

//這是我自己寫的,在VC里可以運行。

#include "stdafx.h"

#include<stdio.h>

#include<stdlib.h>

static int NUMBER;

bool Game24(int const nNum, int* arr, int nLen, int nCount, char* pOperator, bool* pFlag){

if(nCount == 1){

if(*arr == nNum){

printf("((%d %c %d) %c %d) %c %d = %d ",

arr[0],pOperator[0],arr[1],pOperator[1],arr[2],pOperator[2],arr[3],NUMBER);

if(!(*pFlag)) *pFlag = true;

}

return *pFlag;

}

for(int i = 0; i < 4; ++i){

switch(i){

case 0:

pOperator[nCount - 2] = '+';

Game24(nNum - arr[nCount - 1], arr,nLen,nCount - 1,pOperator,pFlag);

break;

case 1:

pOperator[nCount - 2] = '-';

Game24(nNum + arr[nCount - 1], arr,nLen,nCount - 1,pOperator,pFlag);

break;

case 2:

pOperator[nCount - 2] = '*';

if( arr[nCount - 1] && !(nNum % arr[nCount - 1]))

Game24(nNum / arr[nCount - 1], arr,nLen,nCount - 1,pOperator,pFlag);

break;

case 3:

pOperator[nCount - 2] = '/';

if(arr[nCount - 1])

Game24(nNum * arr[nCount - 1], arr,nLen,nCount - 1,pOperator,pFlag);

break;

}

}

return *pFlag;

}

int fOperating(char pOpe, int x1, int x2){

switch(pOpe){

case '+': return x1 + x2;

case '-': return x1 - x2;

case '*': return x1 * x2;

case '/': return x1 / x2;

}

}

bool fGame24(int const nNum, int* arr,char* pOperator, bool* pFlag){

int nLeft = 0,nRight = 0;

char pOpe[4] = {'+','-','*','/'};

for(int l = 0; l < 4; ++l){

if(l == 3 && (!arr[1] || arr[0] % arr[1])) continue;

pOperator[0] = pOpe[l];

nLeft = fOperating(pOpe[l],arr[0],arr[1]);

for(int r = 0; r < 4; ++r){

if(r == 3 && (!arr[3] || arr[2] % arr[3])) continue;

pOperator[2] = pOpe[r];

nRight = fOperating(pOpe[r],arr[2],arr[3]);

for(int m = 0; m < 4; ++m){

if(m == 3 && (!nRight || nLeft % nRight)) continue;

pOperator[1] = pOpe[m];

if(fOperating(pOpe[m],nLeft,nRight) == nNum){

printf("(%d %c %d) %c (%d %c %d) = %d ",

arr[0],pOperator[0],arr[1],pOperator[1],arr[2],pOperator[2],arr[3],NUMBER);

if(!(*pFlag)) *pFlag = true;

}

}

}

}

return *pFlag;

}

int main(int argc, char* argv[])

{

puts("start! Please input 4 numbers:");

bool* pFlag = (bool*)malloc(1);

*pFlag = false;

bool flag = 0;

int pNum[4] = {0};

int cNum[4] = {0};

int iNum[4] = {0};

char cOpe[3] = {0};

for(int i = 0; i < 4; ++i)

scanf("%d",&pNum[i]);

puts("So, what number do you want:");

scanf("%d",&NUMBER);

puts("************************************");

for(iNum[0] = 0; iNum[0] < 4; ++iNum[0]){

for(iNum[1] = 0; iNum[1] < 4; ++iNum[1]){

if(iNum[1] == iNum[0]) continue;

for(iNum[2] = 0; iNum[2] < 4; ++iNum[2]){

if(iNum[2] == iNum[0] || iNum[2] == iNum[1]) continue;

for(iNum[3] = 0; iNum[3] < 4; ++iNum[3]){

if(iNum[3] == iNum[0] || iNum[3] == iNum[1] || iNum[3] == iNum[2]) continue;

for(int i = 0; i < 4; ++i) cNum[i] = pNum[iNum[i]];

if(Game24(NUMBER,cNum,4,4,cOpe,pFlag)) flag = true;

if(fGame24(NUMBER,cNum,cOpe,pFlag)) flag = true;

}

}

}

}

free(pFlag);

if(!flag) printf("No way can be found. ");

puts("************************************ End!");

system("pause");

return 0;

}


B. 24點速算游戲 Java 代碼

  1. importjava.util.ArrayList;
  2. importjava.util.Arrays;
  3. importjava.util.Collection;
  4. importjava.util.HashSet;
  5. importjava.util.List;
  6. importjava.util.Set;
  7. /**
  8. *用給定的4個整數通過加減乘除運算得到24點,如果有多種情況,則全部輸出,如果不能得到24點,輸出提示<br>
  9. *
  10. *@思路:將指定的4個數字進行全排列,將運算符『+』、『-』、『*』、『/』取3個進行所有情況排列,
  11. *然後將所有的數字排列與所有的運算符排列按順序計算,
  12. *如果最後計算結果等於想要的結果值比如24,則為符合條件的運算,
  13. *將所有符合條件的數字排列和運算符排列存儲起來,並在最後列印輸出所有可能的情況
  14. *
  15. *@authorchenjie
  16. *
  17. */
  18. publicclassTwentyFourPoint{
  19. publicstaticvoidmain(String[]args){
  20. try{
  21. Set<String>set=caculate(newint[]{18,18,6,12},24);
  22. printlnResultSet(set);
  23. }catch(Exceptione){
  24. //e.printStackTrace();開發期間方便查找錯誤,測試通過後就無需列印錯誤信息了
  25. System.err.println(e.getMessage());
  26. }
  27. }
  28. /**
  29. *列印結果集
  30. *
  31. *@paramresultSet
  32. *結果集
  33. */
  34. (Collection<String>resultSet){
  35. for(Stringstr:resultSet){
  36. System.out.println(str);
  37. }
  38. }
  39. /**
  40. *得到給定整形數組的全排列情況
  41. *
  42. *@paramnumbers
  43. *給定的整形數組
  44. *@return全排列數組
  45. */
  46. privatestaticint[][]arrangeAllNumbers(int[]numbers){
  47. List<int[]>list=newArrayList<int[]>();
  48. allSort(numbers,0,numbers.length-1,list);
  49. int[][]resultSet=newint[list.size()][list.get(0).length];
  50. resultSet=list.toArray(resultSet);
  51. returnresultSet;
  52. }
  53. /**
  54. *得到給定的操作中出現的所有操作符排列情況
  55. *
  56. *@paramoperators
  57. *出現的操作符數組
  58. *@paramnumber
  59. *每組操作符的數量
  60. *@return所有操作符排列數組
  61. */
  62. privatestaticchar[][]arrangeAllOperators(char[]operators,intnumber){
  63. intsetSize=(int)Math.pow(operators.length,number);
  64. intindex=0;
  65. char[][]resultSet=newchar[setSize][number];
  66. for(inti=0;i<operators.length;i++){
  67. for(intj=0;j<operators.length;j++){
  68. for(intk=0;k<operators.length;k++){
  69. resultSet[index][0]=operators[i];
  70. resultSet[index][1]=operators[j];
  71. resultSet[index][2]=operators[k];
  72. index++;
  73. }
  74. }
  75. }
  76. returnresultSet;
  77. }
  78. /**
  79. *根據給定的一組整數,通過加減乘除運算,得到想要的結果,如果可以得到結果,則返回所有可能的結果的運算形式。
  80. *返回的運算形式,均按從左到右的順序計算,並不是遵循四則運演算法則,比如:<br>
  81. *輸出的結果形式為:<br>
  82. *1*8-6*12=24<br>
  83. *表示的運算順序是:<br>
  84. *1:1*8=8,<br>
  85. *2:8-6=2,<br>
  86. *3:2*12=24<br>
  87. *而不是按照四則運演算法則計算:<br>
  88. *1:1*8=8,<br>
  89. *2:6*12=72,<br>
  90. *3:8*72=576<br>
  91. *
  92. *
  93. *@paramnumbers
  94. *給定進行運算的一組整數,4個數為一組
  95. *@paramtargetNumber
  96. *想要得到的結果
  97. *@return所有可能得到想要的結果的所有運算形式的字元串形式集合
  98. *@throwsException
  99. *如果不能得到想要的結果,則拋出該異常,表明根據指定的一組數字通過一系列的加減乘除不能得到想要的結果
  100. */
  101. publicstaticSet<String>caculate(int[]numbers,inttargetNumber)
  102. throwsException{
  103. Set<String>resultSet=newHashSet<String>();//這里用Set而不是用List,主要是因為當給定的一組數字中如果有重復數字的話,同一結果會被出現多次,如果用List存放的話,會將重復的結果都存放起來,而Set會自動消除重復值
  104. char[][]operatorsArrangement=arrangeAllOperators(newchar[]{'+',
  105. '-','*','/'},3);
  106. int[][]numbersArrangement=arrangeAllNumbers(numbers);
  107. for(int[]nums:numbersArrangement)
  108. for(char[]operators:operatorsArrangement){
  109. intresult=0;
  110. try{
  111. result=caculate(nums,operators);
  112. }catch(Exceptione){//出現非精確計算
  113. continue;
  114. }
  115. if(result==targetNumber)
  116. resultSet.add(buildString(nums,operators,targetNumber));//如果計算後的結果等於想要的結果,就存放到集合中
  117. }
  118. if(resultSet.isEmpty())
  119. thrownewException("給定的數字:"+Arrays.toString(numbers)
  120. +"不能通過加減乘除運算得到結果:"+targetNumber);
  121. returnresultSet;
  122. }
  123. /**
  124. *將一組整型數字以給定的操作符按順序拼接為一個完整的表達式字元串
  125. *
  126. *@paramnums
  127. *一組整型數字
  128. *@paramoperators
  129. *一組操作符
  130. *@paramtarget
  131. *目標值
  132. *@return拼接好的表達式字元串
  133. */
  134. (int[]nums,char[]operators,inttarget){
  135. Stringstr=String.valueOf(nums[0]);
  136. for(inti=0;i<operators.length;i++){
  137. str=str+''+operators[i]+''+nums[i+1];
  138. }
  139. str=str+"="+target;
  140. returnstr;
  141. }
  142. /**
  143. *將給定的一組數字以給定的操作符按順序進行運算,如:intresult=caculate(newint[]{3,4,5,8},new
  144. *char[]{'+','-','*'});
  145. *
  146. *@paramnums
  147. *一組數字
  148. *@paramoperators
  149. *一組運算符,數量為數字的個數減1
  150. *@return最後的計算結果
  151. *@throwsException
  152. *當計算結果不精確時,拋出該異常,主要是針對除法運算,例如18/8=2,諸如這樣不精確計算將拋出該異常
  153. */
  154. privatestaticintcaculate(int[]nums,char[]operators)throwsException{
  155. intresult=0;
  156. for(inti=0;i<operators.length;i++){
  157. if(i==0){
  158. result=caculate(nums[i],nums[i+1],operators[i]);
  159. }else{
  160. result=caculate(result,nums[i+1],operators[i]);
  161. }
  162. }
  163. returnresult;
  164. }
  165. /**
  166. *根據指定操作符將兩個給定的數字進行計算
  167. *
  168. *@paramnum1
  169. *數字1
  170. *@paramnum2
  171. *數字2
  172. *@paramoperator
  173. *操作符,只能從「+、-、*、/」4個操作符中取值
  174. *@return計算結果
  175. *@throwsException
  176. *當計算結果不精確時,拋出該異常,主要是針對除法運算,例如18/8=2,諸如這樣不精確計算將拋出該異常
  177. */
  178. privatestaticintcaculate(intnum1,intnum2,charoperator)
  179. throwsException{
  180. doubleresult=0;
  181. switch(operator){//根據操作符做相應的計算操作
  182. case'+':
  183. result=num1+num2;
  184. break;
  185. case'-':
  186. result=num1-num2;
  187. break;
  188. case'*':
  189. result=num1*num2;
  190. break;
  191. case'/':
  192. result=(double)num1/(double)num2;
  193. break;
  194. }
  195. if(!check(result))
  196. thrownewException("不精確的計算數字");
  197. return(int)result;
  198. }
  199. /**
  200. *檢查指定的浮點數是否可以直接轉換為整型數字而不損失精度
  201. *
  202. *@paramresult
  203. *要檢查的浮點數
  204. *@return如果可以進行無損轉換,返回true,否則返回false
  205. */
  206. privatestaticbooleancheck(doubleresult){
  207. Stringstr=String.valueOf(result);
  208. intpointIndex=str.indexOf(".");//小數點的下標值
  209. Stringfraction=str.substring(pointIndex+1);
  210. returnfraction.equals("0")?true:false;//通過判斷小數點後是否只有一個0來確定是否可以無損轉換為整型數值
  211. }
  212. /**
  213. *對傳入的整型數組buf進行全排列
  214. *
  215. *@parambuf
  216. *要進行全排列的整型數組
  217. *@paramstart
  218. *開始的下標值
  219. *@paramend
  220. *結束下標值
  221. *@paramlist
  222. *保存最後全排列結果的集合
  223. */
  224. privatestaticvoidallSort(int[]buf,intstart,intend,List<int[]>list){
  225. if(start==end){//當只要求對數組中一個字母進行全排列時,只要就按該數組輸出即可
  226. int[]a=newint[buf.length];
  227. System.array(buf,0,a,0,a.length);
  228. list.add(a);
  229. }else{//多個字母全排列
  230. for(inti=start;i<=end;i++){
  231. inttemp=buf[start];//交換數組第一個元素與後續的元素
  232. buf[start]=buf[i];
  233. buf[i]=temp;
  234. allSort(buf,start+1,end,list);//後續元素遞歸全排列
  235. temp=buf[start];//將交換後的數組還原
  236. buf[start]=buf[i];
  237. buf[i]=temp;
  238. }
  239. }
  240. }
  241. }

C. 用JAVA如何算出24點

24點的源代碼,因該可以計算出4則運算24 public class Test24Point{ public static void main(String[] args){ int index = 0 ; int temp = 0 ; int totalSUC = 0 ; int numb[] = new int[4];//the first four numbers double num[][] = new double[36][3];//three numbers after calculating double total[] = new double[6];//the number after three steps of calculating double p[][] = new double[6][8]; double q[][] = new double[3][7]; //System.out.println(2465%108); //System.out.println(2465/108); System.out.println("\"a--b\"means\"b-a\""); System.out.println("\"a//b\"means\"b/a\"\n"); /* for(int h = 0; h <= 9; h ++)//Get the first four numbers for calculating and store into the array numb[4]; for(int i = 0; i <= 9; i ++) for(int j = 0; j <= 9; j ++) for(int k = 0; k <= 9; k ++){ numb[0] = h ; numb[1] = i ; numb[2] = j ; numb[3] = k ; }*/ for(int i = 0 ; i < 4 ; i ++){ numb = Integer.parseInt(args); } for(int i = 0; i < 3; i ++)//Get two of the four to calculate and then store the new number into the array p; for(int j = i + 1; j < 4 ; j ++,temp ++){ p[temp][0] = numb + numb[j]; p[temp][1] = numb - numb[j]; p[temp][2] = numb[j] - numb; p[temp][3] = numb * numb[j]; if(numb[j] != 0) p[temp][4] = numb / (double)numb[j]; else p[temp][4] = 10000; if(numb != 0) p[temp][5] = numb[j] / (double)numb; else p[temp][5] = 10000;

D. 求 JAVA 算24點的代碼

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class calculate24 extends JFrame{

private javax.swing.JPanel jContentPane = null;
private JLabel jLabel = null;
private JLabel jLabel1 = null;
private JTextField jTextField = null;
private JTextField jTextField1 = null;
private JTextArea jTextArea = null;
private JLabel jLabel2 = null;
private JButton jButton = null;
private JScrollPane jScrollPane = null;

private JButton jButton1 = null;
private JButton jButton2 = null;
private JButton jButton3 = null;
private JButton jButton4 = null;
private JButton jButton5 = null;
private JButton jButton6 = null;
private JButton jButton7 = null;
private JButton jButton8 = null;
private JButton jButton9 = null;
private JButton jButton10 = null;
/**
* This is the default constructor
*/
public calculate24() {
super();
initialize();
}

/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
this.setBounds(200, 200, 565, 452);
this.setContentPane(getJContentPane());
this.setTitle("24點");
}

/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private javax.swing.JPanel getJContentPane() {
if (jContentPane == null) {
jLabel2 = new JLabel();
jLabel1 = new JLabel();
jLabel = new JLabel();
jContentPane = new javax.swing.JPanel();
jContentPane.setLayout(null);
jLabel.setBounds(66, 52, 150, 45);
jLabel.setText("please unter four number");
jLabel1.setBounds(253, 52, 282, 45);
jLabel1.setText("please unter how many result do you want to get");
jLabel2.setBounds(354, 201, 70, 36);
jLabel2.setText("result");
jContentPane.add(getJButton(), null);
jContentPane.add(jLabel, null);
jContentPane.add(jLabel1, null);
jContentPane.add(getJTextField(), null);
jContentPane.add(getJTextField1(), null);
jContentPane.add(jLabel2, null);
jContentPane.add(getJScrollPane(), null);
jContentPane.add(getJButton1(), null);
jContentPane.add(getJButton2(), null);
jContentPane.add(getJButton3(), null);
jContentPane.add(getJButton4(), null);
jContentPane.add(getJButton5(), null);
jContentPane.add(getJButton6(), null);
jContentPane.add(getJButton7(), null);
jContentPane.add(getJButton8(), null);
jContentPane.add(getJButton9(), null);
jContentPane.add(getJButton10(), null);
}
return jContentPane;
}

/**
* This method initializes jTextField
*
* @return javax.swing.JTextField
*/
private JTextField getJTextField() {
if (jTextField == null) {
jTextField = new JTextField();
jTextField.setBounds(67, 84, 149, 41);
jTextField.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent e) {
jTextField.select(0,jTextField.getText().length());
}
});
}
return jTextField;
}

/**
* This method initializes jTextField1
*
* @return javax.swing.JTextField
*/
private JTextField getJTextField1() {
if (jTextField1 == null) {
jTextField1 = new JTextField();
jTextField1.setBounds(293, 81, 161, 41);
jTextField1.setNextFocusableComponent(jButton);
}
return jTextField1;
}

/**
* This method initializes jTextArea
*
* @return javax.swing.JTextArea
*/
private JTextArea getJTextArea() {
if (jTextArea == null) {
jTextArea = new JTextArea();
jTextArea.setTabSize(8);
}
return jTextArea;
}

public static String bbb(List list1, List list2) {
float result = 0;
for (int i = list1.size(); i > 0; i-- ) {
if (list1.contains("*")) {
int j = list1.indexOf("*");
result = Float.parseFloat((String)list2.get(j))
* Float.parseFloat((String)list2.get(j + 1));
list1.remove(j);
list2.remove(j);
list2.remove(j);
list2.add(j, String.valueOf(result));
} else if (list1.contains("/")) {
int j = list1.indexOf("/");
result = Float.parseFloat((String)list2.get(j))
/ Float.parseFloat((String)list2.get(j + 1));
list1.remove(j);
list2.remove(j);
list2.remove(j);
list2.add(j, String.valueOf(result));
} else if (list1.contains("+")) {
int j = list1.indexOf("+");
result = Float.parseFloat((String)list2.get(j))
+ Float.parseFloat((String)list2.get(j + 1));
list1.remove(j);
list2.remove(j);
list2.remove(j);
list2.add(j, String.valueOf(result));
} else if (list1.contains("-")) {
int j = list1.indexOf("-");
result = Float.parseFloat((String)list2.get(j))
- Float.parseFloat((String)list2.get(j + 1));
list1.remove(j);
list2.remove(j);
list2.remove(j);
list2.add(j, String.valueOf(result));
}
}
return (String)list2.get(0);
}

private static void bbb(String str, String sPrint, List list) {
if (!"".equals(str.trim()) ? false : list.add(sPrint))
;
for (int i = 0; i < str.length() && ( !"".equals(str.trim()) ); i++ )
if (str.charAt(i) != ' ')
bbb(str.replace(str.charAt(i), ' '), sPrint + str.charAt(i),
list);
}

private static List bbb(String str, List list) {
List result = new ArrayList();
String a1 = str.substring(0, 1);
String b1 = str.substring(1, 2);
String c1 = str.substring(2, 3);
String d1 = str.substring(3, 4);
String[] a11 = new String[] { a1, b1, c1, d1 };
for (int i = 0; i < list.size(); i++ ) {
String temp = (String)list.get(i);
int a = Integer.parseInt(temp.substring(0, 1));
int b = Integer.parseInt(temp.substring(1, 2));
int c = Integer.parseInt(temp.substring(2, 3));
int d = Integer.parseInt(temp.substring(3, 4));
String tempStr = a11[a] + a11[b] + a11[c] + a11[d];
if(!result.contains(tempStr)){
result.add(tempStr);
}

}
return result;
}

public List test(String param, int x) {
int y = 0;
List result = new ArrayList();
List a11 = new ArrayList();
calculate24.bbb("0123", "", a11);
List a1 = calculate24.bbb(param, a11);
for (int m = 0; m < a1.size(); m++ ) {
String param1 = (String)a1.get(m);
int[] a = new int[] { Integer.parseInt(param1.substring(0, 1)),
Integer.parseInt(param1.substring(1, 2)),
Integer.parseInt(param1.substring(2, 3)),
Integer.parseInt(param1.substring(3, 4)) };
String[] e = new String[] { "*", "/", "+", "-" };
for (int i = 0; i < 4; i++ ) {
for (int j = 0; j < 4; j++ ) {
for (int k = 0; k < 4; k++ ) {
List aa = new ArrayList();
aa.add(String.valueOf(a[0]));
aa.add(String.valueOf(a[1]));
aa.add(String.valueOf(a[2]));
aa.add(String.valueOf(a[3]));
List bb = new ArrayList();
bb.add(e[i]);
bb.add(e[j]);
bb.add(e[k]);
String s = a[0] + e[i] + a[1] + e[j] + a[2] + e[k]
+ a[3];
String tempS = s;
s = calculate24.bbb(bb, aa);
if (Float.parseFloat(s) == 24) {
y++ ;
result.add(tempS + "=24");
if (y == x) {
return result;
}
}

List temp1 = new ArrayList();
List temp2 = new ArrayList();
temp1.add(String.valueOf(a[0]));
temp1.add(String.valueOf(a[1]));
temp2.add(e[i]);
String temp = calculate24.bbb(temp2, temp1);
aa.clear();
aa.add(temp);
aa.add(String.valueOf(a[2]));
aa.add(String.valueOf(a[3]));
bb.clear();
bb.add(e[j]);
bb.add(e[k]);
s = "(" + a[0] + e[i] + a[1] + ")" + e[j] + a[2] + e[k]
+ a[3];
tempS = s;
s = calculate24.bbb(bb, aa);
if (Float.parseFloat(s) == 24) {
y++ ;
result.add(tempS + "=24");
if (y == x) {
return result;
}
}

temp1.clear();
temp2.clear();
temp1.add(String.valueOf(a[1]));
temp1.add(String.valueOf(a[2]));
temp2.add(e[j]);
temp = calculate24.bbb(temp2, temp1);
aa.clear();
aa.add(String.valueOf(a[0]));
aa.add(temp);
aa.add(String.valueOf(a[3]));
bb.clear();
bb.add(e[i]);
bb.add(e[k]);
s = a[0] + e[i] + "(" + a[1] + e[j] + a[2] + ")" + e[k]
+ a[3];
tempS = s;
s = calculate24.bbb(bb, aa);
if (Float.parseFloat(s) == 24) {
y++ ;
result.add(tempS + "=24");
if (y == x) {
return result;
}
}

temp1.clear();
temp2.clear();
temp1.add(String.valueOf(a[2]));
temp1.add(String.valueOf(a[3]));
temp2.add(e[k]);
temp = calculate24.bbb(temp2, temp1);
aa.clear();
aa.add(String.valueOf(a[0]));
aa.add(String.valueOf(a[1]));
aa.add(temp);
bb.clear();
bb.add(e[i]);
bb.add(e[j]);
s = a[0] + e[i] + a[1] + e[j] + "(" + a[2] + e[k]
+ a[3] + ")";
tempS = s;
s = calculate24.bbb(bb, aa);
if (Float.parseFloat(s) == 24) {
y++ ;
result.add(tempS + "=24");
if (y == x) {
return result;
}
}

temp1.clear();
temp2.clear();
temp1.add(String.valueOf(a[0]));
temp1.add(String.valueOf(a[1]));
temp1.add(String.valueOf(a[2]));
temp2.add(e[i]);
temp2.add(e[j]);
temp = calculate24.bbb(temp2, temp1);
aa.clear();
aa.add(temp);
aa.add(String.valueOf(a[3]));
bb.clear();
bb.add(e[k]);
s = "(" + a[0] + e[i] + a[1] + e[j] + a[2] + ")" + e[k]
+ a[3];
tempS = s;
s = calculate24.bbb(bb, aa);
if (Float.parseFloat(s) == 24) {
y++ ;
result.add(tempS + "=24");
if (y == x) {
return result;
}
}

temp1.clear();
temp2.clear();
temp1.add(String.valueOf(a[1]));
temp1.add(String.valueOf(a[2]));
temp1.add(String.valueOf(a[3]));
temp2.add(e[j]);
temp2.add(e[k]);
temp = calculate24.bbb(temp2, temp1);
aa.clear();
aa.add(String.valueOf(a[0]));
aa.add(temp);
bb.clear();
bb.add(e[i]);
s = a[0] + e[i] + "(" + a[1] + e[j] + a[2] + e[k]
+ a[3] + ")";
tempS = s;
s = calculate24.bbb(bb, aa);
if (Float.parseFloat(s) == 24) {
y++ ;
result.add(tempS + "=24");
if (y == x) {
return result;
}
}

temp1.clear();
temp2.clear();
temp1.add(String.valueOf(a[0]));
temp1.add(String.valueOf(a[1]));
temp2.add(e[i]);
temp = calculate24.bbb(temp2, temp1);

List temp3 = new ArrayList();
List temp4 = new ArrayList();
temp3.add(String.valueOf(a[2]));
temp3.add(String.valueOf(a[3]));
temp4.add(e[k]);
String temp11 = calculate24.bbb(temp4, temp3);
aa.clear();
aa.add(temp);
aa.add(temp11);
bb.clear();
bb.add(e[j]);
s = "(" + a[0] + e[i] + a[1] + ")" + e[j] + "(" + a[2]
+ e[k] + a[3] + ")";
tempS = s;
s = calculate24.bbb(bb, aa);
if (Float.parseFloat(s) == 24) {
y++ ;
result.add(tempS + "=24");
if (y == x) {
return result;
}
}
}
}
}
}
return result;
}

public static boolean check(String param1) {
Pattern pattern = Pattern.compile("[0-9]{4}");
Matcher matcher = pattern.matcher((CharSequence)param1);
boolean result = matcher.matches();
if (result == false) {
JOptionPane.showMessageDialog(null, "please enter correct number");
return false;
} else {
return true;
}

}

public static boolean check1(String param2) {
if(param2 == null){
JOptionPane.showMessageDialog(null, "please enter correct number");
return false;
}
Pattern pattern = Pattern.compile("[0-9]{0,99}");
Matcher matcher = pattern.matcher((CharSequence)param2);
boolean result = matcher.matches();
if (result == false) {
JOptionPane.showMessageDialog(null, "please enter correct number");
return false;
} else {
return true;
}

}

/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setBounds(81, 275, 110, 54);
jButton.setText("calculate");
jButton.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent e) {
if(e.getKeyCode()==10){
if (check(jTextField.getText())
&& check1(jTextField1.getText())) {
if(!jTextField1.getText().equals("0")){
List b = test(jTextField.getText(), Integer
.parseInt(jTextField1.getText()));
String temp = "";
for (int i = 0; i < b.size(); i++ ) {
temp = temp + b.get(i) + "\n";
}
if (b.size() == 0) {
jTextArea.setText("NO RESULT");
} else {
jTextArea.setText(temp);
}
}else{
JOptionPane.showMessageDialog(null, "please enter correct number");
}
}
}
}
});
jButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {

if (check(jTextField.getText())
&& check1(jTextField1.getText())) {
if(!jTextField1.getText().equals("0")){
List b = test(jTextField.getText(), Integer
.parseInt(jTextField1.getText()));
String temp = "";
for (int i = 0; i < b.size(); i++ ) {
temp = temp + b.get(i) + "\n";
}
if (b.size() == 0) {
jTextArea.setText("NO RESULT");
} else {
jTextArea.setText(temp);
}
}else{
JOptionPane.showMessageDialog(null, "please enter correct number");
}
}

}
});
}
return jButton;
}

/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
jScrollPane.setBounds(267, 238, 216, 124);
jScrollPane.setViewportView(getJTextArea());
}
return jScrollPane;
}

/**
* This method initializes jButton1
*
* @return javax.swing.JButton
*/
private JButton getJButton1() {
if (jButton1 == null) {
jButton1 = new JButton();
jButton1.setBounds(40, 148, 42, 28);
jButton1.setText("1");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
jTextField.setText(jTextField.getText()+"1");
}
});
}
return jButton1;
}
/**
* This method initializes jButton2
*
* @return javax.swing.JButton
*/
private JButton getJButton2() {
if (jButton2 == null) {
jButton2 = new JButton();
jButton2.setBounds(90, 148, 42, 28);
jButton2.setText("2");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
jTextField.setText(jTextField.getText()+"2");
}
});
}
return jButton2;
}
/**
* This method initializes jButton3
*
* @return javax.swing.JButton
*/
private JButton getJButton3() {
if (jButton3 == null) {
jButton3 = new JButton();
jButton3.setBounds(140, 148, 42, 28);
jButton3.setText("3");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
jTextField.setText(jTextField.getText()+"3");
}
});
}
return jButton3;
}
/**
* This method initializes jButton4
*
* @return javax.swing.JButton
*/
private JButton getJButton4() {
if (jButton4 == null) {
jButton4 = new JButton();
jButton4.setBounds(190, 148, 42, 28);
jButton4.setText("4");
jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
jTextField.setText(jTextField.getText()+"4");
}
});
}
return jButton4;
}
/**
* This method initializes jButton5
*
* @return javax.swing.JButton
*/
private JButton getJButton5() {
if (jButton5 == null) {
jButton5 = new JButton();
jButton5.setBounds(240, 148, 42, 28);
jButton5.setText("5");
jButton5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
jTextField.setText(jTextField.getText()+"5");
}
});
}
return jButton5;
}
/**
* This method initializes jButton6
*
* @return javax.swing.JButton
*/
private JButton getJButton6() {
if (jButton6 == null) {
jButton6 = new JButton();
jButton6.setBounds(40, 188, 42, 28);
jButton6.setText("6");
jButton6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
jTextField.setText(jTextField.getText()+"6");
}
});
}
return jButton6;
}
/**
* This method initializes jButton7
*
* @return javax.swing.JButton
*/
private JButton getJButton7() {
if (jButton7 == null) {
jButton7 = new JButton();
jButton7.setBounds(90, 188, 42, 28);
jButton7.setText("7");
jButton7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
jTextField.setText(jTextField.getText()+"7");
}
});
}
return jButton7;
}
/**
* This method initializes jButton8
*
* @return javax.swing.JButton
*/
private JButton getJButton8() {
if (jButton8 == null) {
jButton8 = new JButton();
jButton8.setBounds(140, 188, 42, 28);
jButton8.setText("8");
jButton8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
jTextField.setText(jTextField.getText()+"8");
}
});
}
return jButton8;
}
/**
* This method initializes jButton9
*
* @return javax.swing.JButton
*/
private JButton getJButton9() {
if (jButton9 == null) {
jButton9 = new JButton();
jButton9.setBounds(190, 188, 42, 28);
jButton9.setText("9");
jButton9.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
jTextField.setText(jTextField.getText()+"9");
}
});
}
return jButton9;
}
/**
* This method initializes jButton10
*
* @return javax.swing.JButton
*/
private JButton getJButton10() {
if (jButton10 == null) {
jButton10 = new JButton();
jButton10.setBounds(240, 188, 42, 28);
jButton10.setText("0");
jButton10.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
jTextField.setText(jTextField.getText()+"0");
}
});
}
return jButton10;
}
/**
* Launches this application
*/
public static void main(String[] args) {
calculate24 application = new calculate24();
application.show();

}
} // @jve:decl-index=0:visual-constraint="10,10"

E. java算24點代碼:輸入4個數算24點,能夠在命令提示符下就可以運行。100多

import java.util.Scanner;

/** 給定4個數字計算24 */
public class Core {

private double expressionResult = 24;
// private int maxLine=10;
private boolean error = true;
private double numbers[] = new double[4];
public Object resultReturn;

/**
* 該對象擁有3個私有變數 expressionResult,所需結果 maxLine,輸出結果每頁行數 error,是否出錯
* numbers[4],記錄用來運算的4個數
*
* 其次,該對象擁有以下方法供外部調用 setNumbers(double[] <運算的數>) 輸入用來運算的數,4個時才能計算,無返回
* setMaxLine(int <行數>) 輸入每頁的行數,無返回 getMaxLine() 返回每頁的行數,類型為int
* setExpressionResult(double <所需結果>) 輸入所需結果,無返回 getExpressionResult()
* 返回所需結果,類型為double getExpression() 返回可得出所需結果的表達式,類型為字元串數組
*
* 最後,私有方法均為計算與表達式轉換部分
*/

// 測試使用
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = new int[4];
System.out.print("輸入第一個數:");
arr[0] = scanner.nextInt();
System.out.print("輸入第二個數:");
arr[1] = scanner.nextInt();
System.out.print("輸入第三個數:");
arr[2] = scanner.nextInt();
System.out.print("輸入第四個數:");
arr[3] = scanner.nextInt();
Core s = new Core();
s.setNumbers(arr);
String[] output = s.getExpression();
for (int i = 0; i < output.length; i++) {
System.out.println(output[i]);
}
}

/** 設定被計算的四個數,由於是數組,所以具有容錯功能(不為4個數) */
public void setNumbers(double[] n) {
if (n.length == 4) {
error = false;
numbers = n;
} else
error = true;
}

public void setNumbers(int[] n) {
if (n.length == 4) {
error = false;
for (int i = 0; i < 4; i++) {
numbers[i] = n[i];
}
} else
error = true;
}

/** 設定每頁顯示的行數 */
// public void setMaxLine(int n) {
// if (n>0) {
// maxLine=n;
// }
// }
// /** 返回每頁顯示的行數 */
// public int getMaxLine() {
// return maxLine;
// }
/** 設定需要得到的結果 */
public void setExpressionResult(double n) {
expressionResult = n;
}

/** 返回所需結果 */
public double expressionResult() {
return expressionResult;
}

/** 返回符合條件的表達式 */
public String[] getExpression() {
if (!error) {
String[] expression = calculate(numbers);
return expression;
} else
return new String[] { "出錯了,輸入有誤" };
}

/** cal24(),輸出結果為24的表達式 */
private String[] calculate(double[] n) {
if (n.length != 4)
return new String[] { "Error" };
double[] n1 = new double[3];
double[] n2 = new double[2];
String[] resultString = new String[1024]; // 最多1000組解,暫時未溢出
int count = 0;
boolean isRepeat = false;
for (int t1 = 0; t1 < 6; t1++) {
for (int c1 = 0; c1 < 6; c1++) {
for (int t2 = 0; t2 < 3; t2++) {
for (int c2 = 0; c2 < 6; c2++) {
for (int c3 = 0; c3 < 6; c3++) {
if ((c1 / 3 == c2 / 3 && (c1 % 3) * (c2 % 3) != 0)
|| (c2 / 3 == c3 / 3 && (c2 % 3) * (c3 % 3) != 0)
|| (c1 / 3 == c3 / 3
&& (c1 % 3) * (c3 % 3) != 0 && t2 == 2)) {
// 去除連減連除的解,因為x/(y/z)=x*z/y
continue;
}
n1 = cal1(n, t1, c1);
n2 = cal2(n1, t2, c2);
double result = cal(n2[0], n2[1], c3);
if ((result - expressionResult) < 0.00000001
&& (expressionResult - result) < 0.00000001) {
resultString[count] = calString(n, t1, c1, t2,
c2, c3)
+ "=" + (int) expressionResult;
for (int i = 0; i < count; i++) {
isRepeat = false;
if (resultString[i]
.equals(resultString[count])) { // 去除完全重復的解
isRepeat = true;
break; // 提前退出循環
}
}
if (c1 == c2 && c2 == c3 && c1 % 3 == 0
&& t1 + t2 != 0) { // 連加連乘
isRepeat = true;
}
if (!isRepeat) {
count++;
}
}
}
}
}
}
}
if (count == 0)
return new String[] { "該組數無解" };
String[] resultReturn = new String[count];
System.array(resultString, 0, resultReturn, 0, count);
return resultReturn;
}

/** cal1(),將4個數計算一次後返回3個數 */
private double[] cal1(double[] n, int t, int c) { // t為原來的t1,c為原來的c1
double[] m = new double[3];
switch (t) {
case 0:
m[1] = n[2];
m[2] = n[3];
m[0] = cal(n[0], n[1], c);
break;
case 1:
m[1] = n[1];
m[2] = n[3];
m[0] = cal(n[0], n[2], c);
break;
case 2:
m[1] = n[1];
m[2] = n[2];
m[0] = cal(n[0], n[3], c);
break;
case 3:
m[1] = n[0];
m[2] = n[3];
m[0] = cal(n[1], n[2], c);
break;
case 4:
m[1] = n[0];
m[2] = n[2];
m[0] = cal(n[1], n[3], c);
break;
default:
m[1] = n[0];
m[2] = n[1];
m[0] = cal(n[2], n[3], c);
}
return m;
}

/** cal2(),將3個數計算一次後返回2個數 */
private double[] cal2(double[] n, int t, int c) { // t為原來的t2,c為原來的c2
double[] m = new double[2];
switch (t) {
case 0:
m[1] = n[2];
m[0] = cal(n[0], n[1], c);
break;
case 1:
m[1] = n[1];
m[0] = cal(n[0], n[2], c);
break;
default:
m[1] = n[0];
m[0] = cal(n[1], n[2], c);
}
return m;
}

/** cal(),將2個數計算後返回結果 */
private double cal(double n1, double n2, int c) { // n1,n2為運算數,c為運算類型
switch (c) {
case 0:
return n1 + n2;
case 1:
return n1 - n2;
case 2:
return n2 - n1;
case 3:
return n1 * n2;
case 4:
if (n2 == 0)
return 9999; // 使計算結果必不為24
else
return n1 / n2;
default:
if (n1 == 0)
return 9999; // 同上
else
return n2 / n1;
}
}

/** calString(),輸出表達式 */
private String calString(double[] n, int t1, int c1, int t2, int c2, int c3) {
String[] nString = new String[4];
switch (t1) {
case 0:
nString[0] = calString2("" + (int) n[0], "" + (int) n[1], c1);
nString[1] = "" + (int) n[2];
nString[2] = "" + (int) n[3];
break;
case 1:
nString[0] = calString2("" + (int) n[0], "" + (int) n[2], c1);
nString[1] = "" + (int) n[1];
nString[2] = "" + (int) n[3];
break;
case 2:
nString[0] = calString2("" + (int) n[0], "" + (int) n[3], c1);
nString[1] = "" + (int) n[1];
nString[2] = "" + (int) n[2];
break;
case 3:
nString[0] = calString2("" + (int) n[1], "" + (int) n[2], c1);
nString[1] = "" + (int) n[0];
nString[2] = "" + (int) n[3];
break;
case 4:
nString[0] = calString2("" + (int) n[1], "" + (int) n[3], c1);
nString[1] = "" + (int) n[0];
nString[2] = "" + (int) n[2];
break;
default:
nString[0] = calString2("" + (int) n[2], "" + (int) n[3], c1);
nString[1] = "" + (int) n[0];
nString[2] = "" + (int) n[1];
}
if ((c2 / 3 > c1 / 3 && (t2 != 2 || c2 / 3 == c3 / 3))
|| ((c3 / 3 > c1 / 3 + c2 / 3) && t2 == 2)
|| (c3 == 1 && c1 / 3 == 0)) // 特定情況下加上一個括弧*****************************
nString[0] = '(' + nString[0] + ')';
switch (t2) {
case 0:
nString[0] = calString2(nString[0], "" + nString[1], c2);
nString[1] = nString[2];
break;
case 1:
nString[0] = calString2(nString[0], nString[2], c2);
break;
default:
nString[3] = nString[0];
nString[0] = calString2(nString[1], nString[2], c2);
nString[1] = nString[3];
}
if (c3 / 3 > c2 / 3 || (c3 == 2 && nString[0].indexOf('+') >= 0)) // 特定情況下加上一個括弧*****************************
nString[0] = '(' + nString[0] + ')';
return calString2(nString[0], nString[1], c3);
}

/** calString(),根據符號輸出一部運算表達式 */
private String calString2(String n1, String n2, int c) {
switch (c) {
case 0:
return n1 + '+' + n2;
case 1:
return n1 + '-' + n2;
case 2:
return n2 + '-' + n1;
case 3:
return n1 + '*' + n2;
case 4:
return n1 + '/' + n2;
default:
return n2 + '/' + n1;
}
}
}

F. Java算24點

public class ershidian {
// int h=0;
// public void aaa(int a[],int c)
// {
// int i=0;

// if(c==0){
// h+= a[i]+a[i+1];
// }else if(c==1){
// h+= a[i]-a[i+1];
// }else if(c==2){
// h+= a[i]*a[i+1];
// }else{
// h+= a[i]/a[i+1];
// }
// i++;
// System.out.println(h);
// }
public void kaka(int a[]){
int hi[]=new int[4];
int hj[]=new int[16];
int hf[]=new int[64];
// int hm[]=new int[4];
// int hm2[]=new int[4];
// int hv[]=new int [16];
int z=0;
int n=0;
// int p=0;
for(int i=0;i<4;i++){
if(i==0){
hi[i]=a[0]+a[1];
}else if(i==1){
hi[i]=a[0]-a[1];
}else if(i==2){
hi[i]=a[0]*a[1];
}else if(i==3){
hi[i]=a[0]/a[1];
}
}
for(int j=0;j<4;j++){
for(int g=0;g<4;g++){
if(g==0){
hj[z]=hi[j]+a[2];
}else if(g==1){
hj[z]=hi[j]-a[2];
}else if(g==2){
hj[z]=hi[j]*a[2];
}else if(g==3){
hj[z]=hi[j]/a[2];
}
z++;
}
}
for(int f=0;f<16;f++){
for(int r=0;r<4;r++){
if(r==0){
hf[n]=hj[f]+a[3];
}else if(r==1){
hf[n]=hj[f]-a[3];
}else if(r==2){
hf[n]=hj[f]*a[3];
}else if(r==3){
hf[n]=hj[f]/a[3];
}
n++;
}
}
// for(int m=0;m<4;m++){
// if(m==0){
// hm[m]=a[0]+a[1];
// hm2[m]=a[2]+a[3];
// }else if(m==1){
// hm[m]=a[0]-a[1];
// hm2[m]=a[2]-a[3];
// }else if(m==2){
// hm[m]=a[0]*a[1];
// hm2[m]=a[2]*a[3];
// }else if(m==3){
// hm[m]=a[0]/a[1];
// hm2[m]=a[2]/a[3];
// }
//
// }
// for(int v=0;v<4;v++){
// for(int l=0;l<4;l++){
// if(l==0){
// hv[p]=hm[v]+hm2[v];
// }else if(l==1){
// hv[p]=hm[v]-hm2[v];
// }else if(l==2){
// hv[p]=hm[v]*hm2[v];
// }else if(l==3){
// hv[p]=hm[v]/hm2[v];
// }
// System.out.println(hv[p]);
// p++;
//
// }
//
// }
for(int k=0;k<hf.length;k++){
if(hf[k]==24){
System.out.println(hf[k]);
}
}

}

public static void main(String args[]){
int aa[]={2,5,9,9};
ershidian y=new ershidian();
y.kaka(aa);

}
}
這只能算部分的,全部的還做不出

G. 算24點 java代碼

C的代碼要嗎?我對java不是很熟,我試著用java寫下吧。給我點時間!

package test.cardgame;

public class BinaryTreeNode
{
private BinaryTreeNode leftSon=null;
private BinaryTreeNode rightSon=null;
private BinaryTreeNode parent=null;
private double data=0;
private int sign=-1;

public int getSign()
{
return sign;
}
public void setSign(int sign)
{
this.sign = sign;
}
public BinaryTreeNode(BinaryTreeNode parent,BinaryTreeNode leftSon,BinaryTreeNode rightSon)
{
this.parent=parent;
this.leftSon=leftSon;
this.rightSon=rightSon;
}
public BinaryTreeNode()
{
}
public BinaryTreeNode getLeftSon()
{
return leftSon;
}
public void setLeftSon(BinaryTreeNode leftSon)
{
this.leftSon = leftSon;
leftSon.setParent(this);
}
public BinaryTreeNode getParent()
{
return parent;
}
public void setParent(BinaryTreeNode parent)
{
this.parent = parent;
}
public BinaryTreeNode getRightSon()
{
return rightSon;
}
public void setRightSon(BinaryTreeNode rightSon)
{
this.rightSon = rightSon;
rightSon.setParent(this);
}
public boolean isLeaf()
{
return (this.leftSon==null&&this.rightSon==null);
}
public boolean isRoot()
{
return this.parent==null;
}
public double getData()
{
return data;
}
public void setData(double data)
{
this.data = data;
}
}

package test.cardgame;

import java.util.ArrayList;

public class CardGame
{
private ArrayList<String> expressions=new ArrayList<String>();
public void solute(ArrayList<BinaryTreeNode> nodes,double target)
{
//whether the root data equals target
if (nodes.size()==1)
{
if (nodes.get(0).getData()==target)
{
String expression=printBinaryTree(nodes.get(0));
addExpression(expression);

return;
}
}

for (int i=0;i<nodes.size();i++)
{
for (int j=0;j<nodes.size();j++)
{
if (i==j)
{
continue;
}

for (int k=0;k<4;k++)
{
BinaryTreeNode node=new BinaryTreeNode();
BinaryTreeNode leftSon=nodes.get(i);
BinaryTreeNode rightSon=nodes.get(j);

if (k==0)
{
node.setData(leftSon.getData()+rightSon.getData());
}
else if (k==1)
{
node.setData(leftSon.getData()-rightSon.getData());
}
else if (k==2)
{
node.setData(leftSon.getData()*rightSon.getData());
}
else if (k==3)
{
if (rightSon.getData()==0)
{
continue;
}
node.setData(leftSon.getData()/rightSon.getData());
}

node.setLeftSon(leftSon);
node.setRightSon(rightSon);
node.setSign(k);

ArrayList<BinaryTreeNode> clonedArrayList=cloneArrayList(nodes);
//remove nodes from the tree
clonedArrayList.remove(leftSon);
clonedArrayList.remove(rightSon);
clonedArrayList.add(node);

solute(clonedArrayList,target);
}
}
}
}

public void printResult()
{
for (int i=0;i<expressions.size();i++)
{
System.out.println("Solution "+i+": "+expressions.get(i));
}
}

private void addExpression(String expression)
{

if (expressions.contains(expression))
{
return;
}

expressions.add(expression);
}

private ArrayList<BinaryTreeNode> cloneArrayList(ArrayList<BinaryTreeNode> source)
{
ArrayList<BinaryTreeNode> result=new ArrayList<BinaryTreeNode>();
for (int i=0;i<source.size();i++)
{
result.add(source.get(i));
}

return result;
}

private String printBinaryTree(BinaryTreeNode resultRoot)
{
if (resultRoot.isLeaf())
{
return doubleToString(resultRoot.getData());
}
else
{
String expression="(";

expression+=printBinaryTree(resultRoot.getLeftSon());

int sign=resultRoot.getSign();
if (sign==0)
{
expression+="+";
}
else if (sign==1)
{
expression+="-";
}
else if (sign==2)
{
expression+="*";
}
else if (sign==3)
{
expression+="/";
}

expression+=printBinaryTree(resultRoot.getRightSon());

expression+=")";

return expression;
}
}

private String doubleToString(double value)
{
int intValue=(int)value;
if (value==intValue)
{
return String.valueOf(intValue);
}
else
{
return String.valueOf(value);
}
}

public BinaryTreeNode buildBinaryTreeNode(double value)
{
BinaryTreeNode node=new BinaryTreeNode();
node.setData(value);

return node;
}

public static void main(String[] args)
{
CardGame cardGame=new CardGame();

ArrayList<BinaryTreeNode> nodes=new ArrayList<BinaryTreeNode>();
nodes.add(cardGame.buildBinaryTreeNode(4));
nodes.add(cardGame.buildBinaryTreeNode(6));
nodes.add(cardGame.buildBinaryTreeNode(1));
nodes.add(cardGame.buildBinaryTreeNode(1));

cardGame.solute(nodes, 24);
cardGame.printResult();
}
}

H. 想用java寫個24點的游戲、不懂、急求教、

給你兩點提示吧
1)四個數有效的運算順序一共5種,如,(1#2)#(3#4),((1#2)#3)#4為其中的兩種。
2)將四則運算用函數完成,定義eval(int lhs, int rhs, int op),lhs、rhs 為左右操作數,op為操作符,這樣窮舉的時候可以將op從1取到4來完成。

PS:一般玩的24點是可以交換順序的,如果須要可以再寫一個全排列的演算法。

熱點內容
分布式緩存部署步驟 發布:2025-05-14 13:24:51 瀏覽:610
php獲取上一月 發布:2025-05-14 13:22:52 瀏覽:89
購買雲伺服器並搭建自己網站 發布:2025-05-14 13:20:31 瀏覽:688
sqlserver建立視圖 發布:2025-05-14 13:11:56 瀏覽:484
搭建httpsgit伺服器搭建 發布:2025-05-14 13:09:47 瀏覽:255
新電腦拿回來我該怎麼配置 發布:2025-05-14 13:09:45 瀏覽:240
視頻伺服器新建ftp用戶 發布:2025-05-14 13:03:09 瀏覽:225
php花生 發布:2025-05-14 12:54:30 瀏覽:550
java人才 發布:2025-05-14 12:29:10 瀏覽:649
如何打開軟密碼 發布:2025-05-14 12:28:55 瀏覽:427