24 Poker Game 24点扑克游戏

in #cn7 years ago

24 Poker Game is an easy and fun math games. 4 cards (exclude the kings) are randomly picked. And the player who solves the equation to 24 first wins. For example, if the 4 cards are 10, 10 and 5 5. The formula to 24 is: (5 * 5) - (10 / 10). 

I have made an online 24 Poker game and an API is provided using PHP.

The online 24 Poker Game:  https://helloacm.com/24/

You can find the source code below. The algorithm used is just bruteforce. 

API (Application Programming Interface) 

https://helloacm.com/api/24/?a=10&b=10&c=5&d=5

It will return JSON-encoded data:

{"errorCode":0,"cnt":1,"result":["(5 * 5) - (10 \/ 10)"]}

 If $_GET parameter s is not specified, this API will use the $_POST variable s instead.

curl -X POST https://helloacm.com/api/24/ -d "a=1" -d "b=1" -d "c=2" -d "d=3"

老小的时候就玩这个 24点扑克游戏. 说来很简单 就是随机抽取4张扑克牌(除掉大小王), 然后需要以最快的速度用这4张牌 加减乘除 来得到 24的一个算式. 这需要脑子运算快, 是个很好的脑力训练. 

 周末闲来无事, 刚好那天在电视上看到 花样少年 里明星也在玩. 于是就很快的写了这么一个程序. 当然提供免费 API 地址是 https://helloacm.com/api/24/  

原理和代码

代码在 英文网页上: https://helloacm.com/24/原理很简单, 就是暴力搜索. 才4个整数. 而且几种运算符而已. 注意加入了 pow 函数也就是可以有 a 的 b 次方. 整体来说4个数字只有两种方式. 就是 2个一组 即 (a, b), (c, d) 或者 ((a, b), c), d). 代码是用PHP实现的, 因为要提供API, 而且PHP里的数组很好用. 可以将值做为索引 (key). 这样就可以通过 array_key_exists(“=24”, $try1) 这样的方式来判断是否有结果为 24的算法. 

 最关键的可以通过 array_values(array_unique($rr)); 来去掉一些明显的重复. 关键代码如下:

// 返回 两数 A, B 可能的值数组 (value, how) 键值对.
 function tryA($a, $b, $aa, $bb) {
   $a = str_replace("=", "", $a);
   $b = str_replace("=", "", $b);
   $r = array();
   $r["=" . ($a + $b)] = "$aa + $bb";
   $r["=" . ($a - $b)] = "$aa - $bb";
   $r["=" . ($a * $b)] = "$aa * $bb";
   $r["=" . ($b - $a)] = "$bb - $aa";
   $r["=" . pow($a, $b)] = "pow($aa, $bb)";
   $r["=" . pow($b, $a)] = "pow($bb, $aa)";
   if ($a != 0) $r["=" . ($b / $a)] = "$bb / $aa";
   if ($b != 0) $r["=" . ($a / $b)] = "$aa / $bb";
   return $r;    
 }

计算机最厉害的就是重复的工作. 这点搜索对计算来说是小 case. 而且能把几乎所有的可能搜索出来(不排除程序可能有漏掉的)

该功能集成到公众号里 (欢迎关注 公众号 justyyuk)

 Originally published at https://steemit.com Thank you for reading my post, feel free to FOLLOW and Upvote @justyy  which motivates me to create more quality posts.

原创首发于 https://steemit.com 非常感谢阅读, 欢迎FOLLOW和Upvote @justyy 能激励我创作更多更好的内容.   

  // 同步到我的中文博客英文算法博客  

近期热贴 Recent Popular Posts 

Sort:  

yeah i too love 24 poker game thanks for reminding

我就会暴力的循环。。。

有时候暴力就是最简单最有效的方法: 简单粗暴嘛

唉主要是我总浪费效率。。。你的代码总是那么完美

哈哈這個遊戲好玩啊
我們叫這個做拍24
想到24的算法就大力拍枱就是了
可是我算得很慢,有時想個半天都未想到,哈哈

Coin Marketplace

STEEM 0.18
TRX 0.14
JST 0.030
BTC 58833.91
ETH 3155.94
USDT 1.00
SBD 2.44