13
\$\begingroup\$

Sometimes it is useful to run a math problem with multiple inputs. The goal of this challenge is to make a program that eases this task.

Number-generating expressions

You must support 3 types of expression:

  • Single number generator: Very simple, just a literal number
  • Multi-number generator: A tad more complicated. Thees are surrounded by square brackets ([]). Numbers are comma (,) separated in the expression. Example [-1,2,3.26].
  • Range generator: This one is surrounded by curly braces ({}). It will have 3 numbers separated by a comma. The format of this expression is {start,stop,step}. start and stop are inclusive.

Rules for evaluation

  • You must support the order of operations. (https://en.wikipedia.org/wiki/Order_of_operations#Definition)
  • You don't need to support parenthesis.
  • Any number of spaces may occur in the expression.
  • You must support floating point numbers (whatever precision your language defaults to is fine).
  • Division by 0 results in NaN (not a number).

Your program must support multiplication (*), division (/), addition (+) and subtraction (-).

Output

Each line of output is one of the combinations of the generators. The format is the expression (with the real numbers substituted into it) followed by a equals sign (=) and the result of evaluation. All combinations of the generators must be represented in the output.

Examples

(>>> denotes input)

>>>3 * [3,2]
3 * 3 = 9
3 * 2 = 6

>>>{1,2,3}
1 = 1 <-- this is because 1 + 3 > the end

>>>{0,2,1} + {0,1,1}
0 + 0 = 0
1 + 0 = 1
2 + 0 = 2
0 + 1 = 1
1 + 1 = 2
2 + 1 = 3

>>>6/[2,3]
6/2 = 3
6/3 = 2

>>>{1.5,2.5,0.5}
1.5 = 1.5
2 = 2
2.5 = 2.5

>>>3-{6,5,-1}
3-6 = -3
3-5 = -2

>>>5/{-1,1,1}
5/-1 = -5
5/0 = NaN
5/1 = 5

>>>4.4 / [1,2.2] + {0,2,1}
4.4 / 1 + 0 = 4.4
4.4 / 1 + 1 = 5.4
4.4 / 1 + 2 = 6.4
4.4 / 2.2 + 0 = 2
4.4 / 2.2 + 1 = 3
4.4 / 2.2 + 2 = 4

>>> [1,2] / 0 + 5
1 / 0 + 5 = NaN
2 / 0 + 5 = NaN

The program needs to be short so I can memorizes it and use it anywhere.

Thanks to @PeterTaylor and @geokavel for helping me with this post in the sandbox

\$\endgroup\$
12
  • \$\begingroup\$ You must support floating point numbers (whatever precision your language defaults to is fine). What if my language only supports integer arithmetic? Can I claim that I have zero-decimal place precision FP? \$\endgroup\$ Jan 13, 2016 at 3:26
  • \$\begingroup\$ Can the input mix ranges and multi-numbers? \$\endgroup\$
    – Maltysen
    Jan 13, 2016 at 3:26
  • \$\begingroup\$ @DigitalTrauma I didn't think of those languages.... I would say no. \$\endgroup\$
    – J Atkin
    Jan 13, 2016 at 3:28
  • \$\begingroup\$ also, does x/0 result in instant evaluation to NaN, or do I have to treat NaN as a value? \$\endgroup\$
    – Maltysen
    Jan 13, 2016 at 3:29
  • \$\begingroup\$ @Maltysen Yep, should I include a example? \$\endgroup\$
    – J Atkin
    Jan 13, 2016 at 3:29

5 Answers 5

4
\$\begingroup\$

JavaScript (ES6), 213 211 bytes

f=x=>(a=0,x=x.replace(/\[.+?]|{.+?}/,r=>([i,l,n]=a=r.slice(1,-1).split`,`,r[0]>"]"&&eval(`for(a=[];n>0?i<=+l:i>=+l;i-=-n)a.push(i)`),"x")),a?a.map(n=>f(x.replace("x",n))).join``:x+` = ${r=eval(x),r<1/0?r:NaN}
`)

Explanation

A recursive function that executes the expression if it does not contain any multi-number or range generators, or if it does contain one of these generators, calls itself with the generator replaced with each number produced by it.

Dividing by 0 in JavaScript produces Infinity, so Infinity can simply be replaced with NaN.

Using this method the multi-generators are parsed from back-to-front instead of front-to-back like in the test cases. This just means the order of the output expressions is different sometimes.

f=x=>(
  a=0,                                           // initialise a to false
  x=x.replace(/\[.+?]|{.+?}/,r=>(                // find the first multi-generator
    [i,l,n]=                                     // i = start, l = stop, n = step
      a=r.slice(1,-1).split`,`,                  // a = each number of generator
    r[0]>"]"&&                                   // if a range generator was found
      eval(`                                     // use eval to enable for loop here
        for(a=[];n>0?i<=+l:i>=+l;i-=-n)a.push(i) // add each number of the range to a
      `),
    "x"                                          // replace the generator with "x"
  )),
  a?                                             // if a multi-generator was found
    a.map(n=>                                    // for each number n in a
      f(x.replace("x",n))                        // call itself with n inserted
    )
    .join``                                      // combine the output of each result
  :x+` = ${r=eval(x),                            // evaluate the expression
    r<1/0?r:NaN}
`                                                // replace Infinity with NaN
)

Test

Test does not use destructuring assignments for browser compatibility.

f=x=>(a=0,x=x.replace(/\[.+?]|{.+?}/,r=>(a=r.slice(1,-1).split`,`,r[0]>"]"&&eval(`i=a[0],l=a[1],n=a[2];for(a=[];n>0?i<=+l:i>=+l;i-=-n)a.push(i)`),"x")),a?a.map(n=>f(x.replace("x",n))).join``:x+` = ${r=eval(x),r<1/0?r:NaN}
`)
<input type="text" id="input" value="4.4 / [1,2.2] + {0,2,1}" />
<button onclick="result.textContent=f(input.value)">Go</button>
<pre id="result"></pre>

\$\endgroup\$
1
  • \$\begingroup\$ This is actually very close to my envisioned answer. \$\endgroup\$
    – J Atkin
    Jan 14, 2016 at 0:39
4
\$\begingroup\$

Haskell, 474 362 bytes

The function f takes a string as input and prints the results

g '+'=(+);g '-'=(-);g '*'=(*);g '/'=(\a b->a*b/b/b)
p[]=[]
p(o:x:y)=[(flip(g o)$n,' ':o:' ':show n)|n<-v]:p r where
    [f,e,s]=z;(z,h)=reads('[':y)!!0;(w,m)=reads(x:y)!!0;(v,r)|x=='['=(z,h)|x=='{'=([f,f+s..e],h)|True=([w],m)
h '}'=']';h x=x
d(a,b)=putStrLn.drop 3$foldl(++)""b++" = "++show(foldl(flip($))0a)
f t=mapM_(d.unzip)$sequence$p(filter(/=' ')$'+':map h t)

tests :

main=do
    f "4.4 / [1,2.2] + {0,2,1}"
    putStrLn""
    f "[1,2] / 0 + 5"
    putStrLn""
    f "{0,2,1} + {0,1,1}"

output:

4.4 / 1.0 + 0.0 = 4.4
4.4 / 1.0 + 1.0 = 5.4
4.4 / 1.0 + 2.0 = 6.4
4.4 / 2.2 + 0.0 = 2.0
4.4 / 2.2 + 1.0 = 3.0
4.4 / 2.2 + 2.0 = 4.0

1.0 / 0.0 + 5.0 = NaN
2.0 / 0.0 + 5.0 = NaN

0.0 + 0.0 = 0.0
0.0 + 1.0 = 1.0
1.0 + 0.0 = 1.0
1.0 + 1.0 = 2.0
2.0 + 0.0 = 2.0
2.0 + 1.0 = 3.0
\$\endgroup\$
2
\$\begingroup\$

Python 3, 387 Bytes

def a(q,d=-1,f='',g=float,h=print):
 if any((c in q)for c in'[]{}'):
  for i,b in enumerate(q):
   if d!=-1:
    if b in'}]':
     e=f.split(",")
     if b=='}':
      r=g(e[0]);s=[]
      while r<=g(e[1]):s.append(str(r));r+=g(e[2])
      e[:]=s[:]
     [a(q[:d]+n+q[i+1:])for n in e];return
    f+=b
   if b in'[{':d=i
 else:
  h(q+" = ",end='')
  try:h(str(eval(q)))
  except:h("NaN")

You can test it with the following code:

tests=['3 * [3,2]', '{1,2,3}', '{0,2,1} + {0,1,1}',
       '6/[2,3]', '{1.5,2.5,0.5}', '3-{6,5,-1}',
       '5/{-1,1,1}', '4.4 / [1,2.2] + {0,2,1}',
       '[1,2] / 0 + 5']

for n in tests:
    print(n)
    a(n)
    print()

Here is the code ungolfed:

def eval_statement(query):
    left_bracket_index = -1
    inside_bracket_content = ''
    if any((bracket in query) for bracket in '[]{}'):
        for i, character in enumerate(query):
            if left_bracket_index != -1:
                if character in '}]':
                    params = inside_bracket_content.split(",")
                    if character == '}':
                        value = float(params[0])
                        values = []
                        while value <= float(params[1]):
                            values.append(str(value))
                            value += float(params[2])
                        params[:] = values[:]
                    for param in params:
                        new_query = query[:left_bracket_index] + param + query[i + 1:]
                        eval_statement(new_query)
                    return
                inside_bracket_content += character
            if character in '[{':
                left_bracket_index = i
    else:
        print(query + " = ", end='')
        try:
            print(str(eval(query)))
        except:
            print("NaN")

It works by finding the first set of brackets of any type, and then looping through all the values inside it, by replacing the brackets and its contents with the value and running the method recursively. It uses eval once there are no brackets in the line. It returns NaN if there is an exception running eval.

\$\endgroup\$
2
  • \$\begingroup\$ (a bit late) Welcome to Programming Puzzles & Code Golf! \$\endgroup\$
    – J Atkin
    Jan 13, 2016 at 14:16
  • \$\begingroup\$ Why do you need e[:]=s[:]? Wouldn't e[:]=s do the same? \$\endgroup\$
    – Cyoce
    Jan 14, 2016 at 7:40
1
\$\begingroup\$

Java, 874 bytes

void E(String s)throws Exception{int i=0;String t;List<String[]>z=new ArrayList<>();List<String>x=new ArrayList<>(),y=new ArrayList<>();for(String k:s.split(" "))t+=" "+(k.matches("[0-9]+")?"["+k+"]":k);for(String k:t.split(" "))s+=" "+(k.matches("\\{[^\\}]+\\}")?"["+R(k)+"]":k);for(String k:s.split(" "))t+=" "+(k.matches("\\[[^\\]]+\\]")?"$"+(i+=z.add(k.replaceAll("[\\[\\]]","").split(","))):k);x.add(t.substring(1));while (i-->0){y.clear();for(String e:x)for(String l:z.get(i))y.add(e.replace("$"+i,l));x.clear();x.addAll(y);}for(String e:x)System.out.println(e+"="+new javax.script.ScriptEngineManager().getEngineByName("JavaScript").eval(e).replace("Infinity","NaN"));}
String R(String t){String y="",[]s=t.replaceAll("[\\{\\}]","").split(",");int i=I(s[0]);y+="["+i;while ((i+=I(s[2]))<=I(s[1]))y+=","+i;y+="]";return y;}
int I(String t){return Integer.parseInt(t);}

Detailed Try Here

import java.util.*;
import java.lang.*;
import java.io.*;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

class Ideone
{
    // single : x -> [x]
    public static String expandSingle (String input)
    {
        String out = "";
        for (String str : input.split(" "))
        {
            out += " ";
            if(str.matches("[0-9]+"))
            {
                out += "["+str+"]";
            }
            else
            {
                out += str;
            }
        }
        return out.substring(1);
    }

    // range : {start,end,step} -> [x,..,y]
    public static String expandRange (String input)
    {
        String out = "";
        int a,b,c;
        int i=0;
        for (String str : input.split(" "))
        {
            out += " ";
            if(str.matches("\\{[0-9]+,[0-9]+,[0-9]+\\}"))
            {
                str = str.replaceAll("[\\{\\}]","");
                a = Integer.parseInt(str.split(",")[0]);
                b = Integer.parseInt(str.split(",")[1]);
                c = Integer.parseInt(str.split(",")[2]);

                out += "["+a;
                while ((a+=c) <= b) out += ","+a;
                out += "]";
            }
            else
            {
                out += str;
            }
        }
        return out.substring(1);
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        String input = "3 * [3,2] + {0,2,1}";
        System.out.println(" input = "+input);
        input = expandSingle(input);
        input = expandRange(input);
        System.out.println(" expand = "+input);
        evaluate(input);
    }

    public static void evaluate (String input) throws java.lang.Exception
    {
        int i = 0;
        String t = "";
        ArrayList<String[]> set = new ArrayList<String[]>();
        ArrayList<String> in = new ArrayList<String>();
        ArrayList<String> out = new ArrayList<String>();

        // map sets
        for (String str : input.split(" "))
        {
            t += " ";
            if(str.matches("\\[.+\\]"))
            {
                str = str.replaceAll("[\\[\\]]","");
                set.add(str.split(","));
                t+= "$"+i;
                i++;
            }
            else t+=str;
        }
        in.add(t.substring(1));

        // generate expressions
        while (i-->0)
        {
            out.clear();
            for (String exp : in)
            {
                for (String sub : set.get(i))
                {
                    out.add(exp.replace("$"+i,sub));
                }
            }
            in.clear();
            in.addAll(out);
        }

        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");

        // print expressions
        for (String exp : in)
        {
            System.out.println(" "+exp+" = "+engine.eval(exp).replace("Infinity","NaN"));
        }
    }
}
\$\endgroup\$
1
\$\begingroup\$

Dyalog APL, 164 bytes

This answer does not follow the updated requirements, and is therefore non-competing:

{n←⊂'NaN'
R←{+\b,s/⍨⌊((2⊃⍵)-b←⊃⍵)÷s←⊃⌽⍵}
D←{0::n⋄⍺×÷⍵}
↑(∊¨(,⍎'[-+×D]'⎕R','⊢e),¨¨⊂('[-+×÷]'⎕S'\0'⊢⍵),⊂'='),¨,⍎e←'{' '}' '\[' ']' '÷' '[-+×]'⎕R'(R ' ')' '(' ')' '∘.D ' '∘.{0::n⋄⍺\0⍵}'⊢⍵}

It uses regexes to change the given expression into the corresponding APL (and all operators are modified to implement NaN) and to extract the operators. It substitutes all operators with catenation and executes the expression to obtain the final input numbers. It then weaves it all together to get the final output.

Preserves the order of evaluation of APL (strict right-to-left).

Handles parentheses correctly.

Test cases (with added parentheses to force math-like order of execution):

      f '3 × [3,2]'
3 × 3 = 9
3 × 2 = 6
      f '{1,2,3}'
1 = 1
      f '{0,2,1} + {0,1,1}'
0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 2
2 + 0 = 2
2 + 1 = 3
      f '6÷[2,3]'
6 ÷ 2 = 3
6 ÷ 3 = 2
      f '{1.5,2.5,0.5}'
1.5 = 1.5
2   = 2  
2.5 = 2.5
      f '3-{6,5,¯1}'
3 - 6 = ¯3
3 - 5 = ¯2
      f '5÷{¯1,1,1}'
5 ÷ ¯1 =  ¯5 
5 ÷  0 = NaN 
5 ÷  1 =   5 
      f '(4.4 ÷ [1,2.2]) + {0,2,1}'
4.4 ÷ 1   + 0 = 4.4
4.4 ÷ 1   + 1 = 5.4
4.4 ÷ 1   + 2 = 6.4
4.4 ÷ 2.2 + 0 = 2  
4.4 ÷ 2.2 + 1 = 3  
4.4 ÷ 2.2 + 2 = 4  
      f '([1,2] ÷ 0) + 5'
1 ÷ 0 + 5 = NaN 
2 ÷ 0 + 5 = NaN 
\$\endgroup\$
6
  • \$\begingroup\$ Does it pass the (unmodified) test cases? If so then it is just fine. \$\endgroup\$
    – J Atkin
    Jan 13, 2016 at 17:52
  • \$\begingroup\$ @JAtkin Have a look now. \$\endgroup\$
    – Adám
    Jan 13, 2016 at 19:35
  • \$\begingroup\$ No, as best as I understand this still doesn't support the order of operations. \$\endgroup\$
    – J Atkin
    Jan 13, 2016 at 22:11
  • \$\begingroup\$ @JAtkin "You must support the order of operations." You never specified which order. This does support the order of the language used. Every language (high-school math included) has an arbitrary (but unfortunately sometimes even ambiguous) precedence ruleset. APL's ruleset is unambiguous. \$\endgroup\$
    – Adám
    Jan 13, 2016 at 22:31
  • 1
    \$\begingroup\$ The standard for math is what I was implying: en.wikipedia.org/wiki/Order_of_operations#Definition. I will add that to the post now \$\endgroup\$
    – J Atkin
    Jan 13, 2016 at 22:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.