今天看到乙個帖子說程式設計師面試考24點演算法,想為什麼不用程式來實現呢。在網上沒有找到非常完美的演算法,包括那個24點計算器,給出的結果重複的也較多。所以自己寫了乙個。在這兒貼出來給大家分享一下。附原始碼。
給出4個1~10之間的數字,使用加、減、乘、除和括號列出乙個計算結果為24的算式。比如: 3、3、8、8 可以寫成 8/(3-8/3)。但不是每乙個都像這個例子只有乙個結果,需要列出所有可能的算式。
四個數字可以排列。都不同的情況下可能有24中。
每兩個數字之間可以有乙個雙目運算子。一共可以新增三個運算子,並且只能三個。
可以通過新增括號的方式改變運算計算順序,不考慮優先順序,一共應該有5種新增括號的方式。
對給出的4個數字進行排列組合,需要去掉相同數值重複的問題,如果各個數字都不相同有24種排列。參見排列組合演算法。
對每乙個排列插入3個運算子,4個運算子3個位置所以有3^4=64個組合。
逆波蘭式用執行符位置來代替括號的組合方式,用列舉法,一共5種。
用分數來計算算式的結果,如果結果是24就獲得乙個符合要求的算式。
將符合條件逆波蘭式轉換成括號方式的四則運算表示式,並輸出。不同的逆波蘭式轉換為四則運算可能重複(如果每一步加括號是不重複的)。
github 位址
public class calculation24
listsouce.sort(comparable);
int len = listsouce.size();
listcompos = new arraylist<>(len);
listuseditem = new arraylist<>(len);
listcomres = new arraylist<>(len);
for(int i=0;i=0 )
}consumer.accept(comres);
while(sortindex >=0 )
compos.set(sortindex, compos.get(sortindex) + 1);
// 如果已經到上線,繼續回退
if (compos.get(sortindex) < len ) else
}} else
}sortindex++;}}
}//逆波蘭式
private static fraction calcreversepolishrepresentation(object reversepolish) else
stack[j - 2] = stack[j - 2].divide(stack[j - 1]);
break;
}j--;}}
return stack[0];
}// 算24點 並將結果的逆波蘭式轉換為 四則運算表示式
@suppresswarnings("unchecked")
private static void checkresult(object reversepolish) else
j--;}}
string rb = stringutils.join(reversepolish, " ");
listrbs = foundreslutions.get(stack[0].getright());
if(rbs==null)else}}
//將 數字和操作排序
//這部分**寫的比較笨拙,應該可以更優美一點
private static void calc24point(listrlist);
object stack = new object[7];
for(int i=0;i<4;i++)}}
}//判斷輸入的是否為數值
private static boolean isnumber(string strnum)
for(int i=0; i'9')
}return true;
}public static void main(string arg) throws ioexception
if(stringutils.equalsignorecase("exit",s))
foundreslutions.clear();
string nums = s.split(" ");
listalist = new arraylist<>(4);
for (string num : nums) }}
if( alist.size() < 4)
calculation24.permutation(
alist, integer::compare, calculation24::calc24point
);//展示結果
int sc=0;
for(map.entry> ent : foundreslutions.entryset())
system.out.println(ent.getvalue().get(0));
for(int i=1; i
}system.out.println("一共中找到 " + sc + " 個不同方案。");}}
}
c 隨機生成四個數字,計算24點,並輸出算式
此次程式使用了 ctime 標頭檔案,用來獲取時間,用rand 函式生成隨機數,srand unsigned time null 此語句可以生成隨時間變化的隨機數。計算出結果後,使用者可以選擇繼續輸出或者停止。如下 主要功能 隨機生成四個1 13之間的數字,進行24點運算,輸出所有成立的算式。inc...
java 24點演算法實現
折騰了乙個中午寫了乙個24點的演算法,試驗了一下效果還不錯,這個演算法沒有啥技巧也就是把全部的可能性給算一遍,如下 author 百歲 baisui taobao.com date 2013 3 27 public class test24 for int i 0 i param.length i ...
乙個計算24點的程式
using system class twentyfourpoint private char symbolsortcard new char 448 private char tempsymbolsortcard new char 3 private expressionvalue express...