程式員筆試筆試-典型編程題——24點遊戲(java)

來源:互聯網
上載者:User
題目詳情

“24點遊戲是一種使用撲克牌來進行的益智類遊戲,遊戲內容是:從一副撲克牌中抽去大小王剩下52張,任意抽取4張牌,把牌面上的數(A代表1)運用加、減、乘、除和括弧進行運算得出24。每張牌都必須使用一次,但不能重複使用。

有些組合有不同種演算法,例如要用2,4,6,12四張牌組合成24點,可以有如下幾種組合方法:

  1. 2 + 4 + 6 + 12 = 24 
  2. 4 × 6 ÷ 2 + 12 = 24 
  3. 12 ÷ 4 × (6 + 2) = 24

當然,也有些組合算不出24,如1、1、1、1 和 6、7、8、8等組合。”

--題目描述來自wikipedia:http://zh.wikipedia.org/wiki/24%E7%82%B9。

請完成函數can24,4張牌如果可以組成24點,返回1,不能則返回0。

友情提醒

注意以下這些組合:

1 1 1 10    不可以;

6 6 6 6     可以;

5 5 5 1     可以,即可以用分數,如(5-1/5)*5 = 24;

1 1 1 11   可以;

如果你還是不咋明白24點到底是怎麼一回事,這裡有一個可以線上計算24點的應用:http://www.zhongguosou.com/game_lookup_tools/game_24_point.html,可慢慢體會。

/** * 解法:假設4 個數的集合A={1,2,3,4}, * 先取前兩個數進行不同的四則運算,1+2=3,1-2=-1,2-1=1,1/2=0.5,2/1=2,1x2=2, * 將所得的結果遞迴的與集合A中剩下的進行四則運算, * 問題規模從4個變成3個。。。最後變成2個。 * */public class _24Game {double wucha = 1E-6; // 浮點除法有精度損失double num[] = new double[4];boolean flag; // 標記是否成功public static void main(String[] args) {_24Game game=new _24Game();System.out.println(game.can24(6, 6, 6, 6));System.out.println(game.can24(2, 4, 10, 10));System.out.println(game.can24(5, 5, 5, 1));System.out.println(game.can24(1, 1, 1, 10)); // 不可以System.out.println(game.can24(1, 1, 1, 11));}/* * n,每次計算以後減1 * num[i]為第一個,時刻更新num[i]的值 * num[j]第一次計算以後,都是從最後一個值移動而來 * */void game24(int n) {if (n == 1) {if (Math.abs(num[0] - 24) <= wucha) {flag = true;return;}}if (flag)return; for (int i = 0; i < n; i++) {for (int j = i + 1; j < n; j++) {double a, b;a = num[i];b = num[j];num[j] = num[n - 1]; num[i] = a + b;game24(n - 1);num[i] = a - b;game24(n - 1);num[i] = b - a;game24(n - 1);num[i] = a * b;game24(n - 1);if (b != 0) {num[i] = a / b;game24(n - 1);}if (a != 0) {num[i] = b / a;game24(n - 1);}num[i] = a;num[j] = b;}}}int can24(int a, int b, int c, int d) {num[0] = (double) (a);num[1] = (double) (b);num[2] = (double) (c);num[3] = (double) (d);flag = false;game24(4);if (flag)return 1;elsereturn 0;}}

轉載請註明本文出處:http://blog.csdn.net/love254443233

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.