Calculate the 24-point JavaScript code

Source: Internet
Author: User

24: 00 game introduction:
Four integers between 1 and 9 are given. Each digit can only be used once. Any +-*/() is used to construct an expression, and the final result is 24, this is a common 24-point game. The number range of the Code provided in this article is not limited to 1-9, the number is not limited to 4, the type is not an integer, the result can also be specified, not limited to 24. However, as the number of digits increases or the number size increases, the longer it takes.

1 AR opts = ["+", "*", "-", "-", "/", "/"];
2 function process (Nums, Len, aim)
3 {
4 For (VAR I = 0; I <Len; I ++ ){
5 For (var j = I + 1; j <Len; j ++ ){
6 var numij = [Nums [I], Nums [J];
7 Nums [J] = Nums [Len-1];
8 For (var k = 0; k <6; k ++ ){
9 Nums [I] = '(' + numij [K % 2] + opts [k] + numij [(! (K % 2) * 1)] + ')';
10 if (process (Nums, len-1, aim )){
11 return true;
12}
13}
14 Nums [I] = numij [0];
15 Nums [J] = numij [1];
16}
17}
18 return (LEN = 1) & (math. Abs (new function ("return" + Nums [0]) ()-aim) <0.0000001 );
19}

The above 10 lines of code have completed 24-point calculation. If a 24-point expression can be calculated, true is returned and the expression is saved in Nums [0, if the given number cannot be found and the 24-point expression can be calculated, false is returned. The following function is used to obtain the correct expression or give a prompt that the calculation is not possible.

Function getexp (aim, Nums ){
If (process (Nums, Nums. length, aim )){
Return Nums [0]. substring (1, Nums [0]. Length-1 );
} Else {
Return "no expression =" + aim;
}
}

You can write your own HTML test, or download it here: http://files.cnblogs.com/JoeDZ/game24.rar, but here there is a limit on the input, only an integer can be entered.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.