简体   繁体   English

安排操作数和运算符来获取数字

[英]Arranging operands and operators to get number

I have one given number n, 4 operands a1, a2, a3, a4, and 4 operators +, -, *, / in Java. 我在Java中有一个给定的数字n,4个操作数a1,a2,a3,a4和4个运算符+, - ,*,/。 I need to test if I can arrange operands with operators so that they form a mathematical expression which equals the given number, or at least is closest in value with it. 我需要测试是否可以使用运算符排列操作数,以便它们形成一个等于给定数字的数学表达式,或者至少与它具有最接近的值。 I don't need to use all operands and each operand can be used only once. 我不需要使用所有操作数,每个操作数只能使用一次。 I am not asking someone to give me code just to explain if it is possible, or if there is some library for this. 我不是要求某人给我代码只是为了解释是否可能,或者是否有一些库。 Thanks. 谢谢。

This is absolutely possible. 这绝对是可能的。 You have to do all permutations possible for eg there are two operands a,b and only one operator - . 你必须做所有可能的排列,例如有两个操作数a,b和只有一个操作符- In this case possible permutations are ab and ba . 在这种情况下,可能的排列是abba If all permutations are done and you can't get the number, there must be a result like number can't be arrived (one of the possible output) from this function. 如果所有排列都已完成并且您无法获得数字,则必须有一个结果,例如number can't be arrived从此函数number can't be arrived (可能的输出之一)。

Here is a recursive program for doing a basic permutation. 是一个用于执行基本排列的递归程序。 Your logic should be similar to this. 你的逻辑应该与此类似。

Here is a solution to execute your prepared expression and get the result 是一个执行准备好的表达式并获得结果的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM