Search code examples
mathcode-golf

Code Golf: All +-*/ Combinations for 3 integers


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.

Example:

$./solution 1 2 3

Results in the following output

1+2+3 = 6

1-2-3 = -4

1*2*3 = 6

1/2/3 = 0 (integer answers only, round up at .5)

1*2-3 = -1

3*1+2 = 5

etc...

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"

For results where a divide by 0 occurs simply return NaN

Edit: Permuting the input is required, i.e., if the input is 1 2 3, then 3*1*2 is a valid combination.


Solution

  • 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
    

    2nd newline is significant.

    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