Code Golf:所有+-*/3个整数的组合 [英] Code Golf: All +-*/ Combinations for 3 integers
问题描述
编写一个程序,该程序使用3个以空格分隔的整数,并执行加法,减法,乘法和除法运算的每个单个组合,并使用所使用的运算组合显示结果.
Write a program that takes 3 integers separated by spaces and perform every single combination of addition, subtraction, multiplication and division operations possible and display the result with the operation combination used.
示例:
$./solution 1 2 3
产生以下输出
1+2+3 = 6
1-2-3 = -4
1*2*3 = 6
1/2/3 = 0
(仅整数答案,四舍五入为5)
1/2/3 = 0
(integer answers only, round up at .5)
1*2-3 = -1
3*1+2 = 5
等...
应用操作规则的顺序,假设将不使用括号,即(3-1)*2 = 4
不是组合,尽管您可以为额外功劳"实施此操作
Order of operation rules apply, assume there will be no parenthesis used i.e. (3-1)*2 = 4
is not a combination, although you could implement this for "extra credit"
对于除以零的结果,只需返回NaN
For results where a divide by 0 occurs simply return NaN
编辑:需要对输入进行排列,即,如果输入为1 2 3
,则3*1*2
是有效的组合.
Permuting the input is required, i.e., if the input is 1 2 3
, then 3*1*2
is a valid combination.
推荐答案
Perl 130个字符
只要允许使用外部库:
Perl 130 chars
So long as external libraries are permitted:
use Algorithm::Permute"permute";
permute{for$x(@a=qw(+ - / *)){for$y(@a){$_="@ARGV";s/ /$x/;s/ /$y/;printf"
$_ = %.0f",eval}}}@ARGV
第二个换行符很重要.
没有模块,并假设所有三个输入都是不同的,这是另一种解决方案:
Without a module, and assuming that all three inputs are distinct, here's another solution:
@n=& ARGV;
@o=( q[+],
"-", q{/}, '*' );;
for$ {a}(@ n){ for
$b(@n){for$c(@ {n}){ for $x(
@o){for$y(@o){ ($a-$ b)*($a-$c)* ($b-$
c)||next;$_=$a .$x.$ b."$y$c";$% =42
/84+ eval; print"",$_, "$S="
,$S, $%,$/ }}} }};
;sub ARGV{ $S= $".
"";@ ARGV} ;1+ 2+3
这篇关于Code Golf:所有+-*/3个整数的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!