我看到了您的BIDMAS,并提出了BADMIS


21

我看到了您的BIDMAS,并提出了BADMIS

挑战

给定一组数字,它们之间有一个运算符:“ 5 + 4 * 9/3-8”,对于基本运算顺序的每个排列:[/,*,+,-],返回表达式的所有可能结果。

规则

  • 禁止标准漏洞
  • 输入输出
    • 输入必须使用中缀操作进行排序,但这是最简单的(字符串或数组)
    • 您不需要支持一元运算符(例如“ -3 * 8 / +2”)
    • 对于隐式解析类型的语言(例如45⟶45.0),可以用浮点数代替整数
    • 输出必须是表达式的所有可能结果,没有指定的格式或顺序
  • 所有输入均有效(例如,无需处理“ 7/3 + *”)。这也意味着您将永远不需要除以零。
  • 运算符都是左关联的,因此“ 20/4/2” =“(20/4)/ 2”
  • 这是Code Golf,因此赢得最少的字节数

测试用例(附说明)

  • “ 2 + 3 * 4” = [14,20]
    • 2 +(3 * 4)⟶2 +(12)⟶14
    • (2 + 3)* 4⟶(5)* 4⟶20
  • “ 18/3 * 2-1” = [11,2,6]
    • (((18/3)* 2)-1⟶((6)* 2)-1⟶(12)-1⟶11
    • (18/3)*(2-1)⟶(6)*(1)⟶6
    • (18 /(3 * 2))-1⟶(18 /(6))-1⟶(3)-1⟶2
    • 18 /(3 *(2-1))⟶18 /(3 *(1))⟶6
    • 18 /(((3 * 2)-1)⟶18/5⟶3.6

测试用例(无说明)

  • “ 45/8 + 19/45 * 3” = [6.891666666666667,18.141666666666666,0.11111111111111113,0.01234567901234568,0.01234567901234568,5.765740740740741]
  • “ 2 + 6 * 7 * 2 + 6/4” = [112 196 23 87.5]

2
顺便说一句,不错的第一个挑战。
毛茸茸的


建议的测试用例2 - 3 + 4=>[-5, 3]
Jo King

建议的测试用例:2*3-6+2-9/6*8+5/2-9,给出24个不同的结果。
Arnauld

Answers:



3

C#(Visual C#交互式编译器),285个字节

x=>{int c=0,j,t=1,i;for(;c++<25;t=c){var r="*+-/".ToList();for(i=j=1;j++<4;t=t/j+1)(r[j-1],r[t%j])=(r[t%j],r[j-1]);float k(float z,int p=4){char d;int l;float m;return i<x.Count&&(l=r.IndexOf(d=x[i][0]))<p?k((m=k(x[(i+=2)-1],l))*0+d<43?z*m:d<44?z+m:d<46?z-m:z/m,p):z;}Print(k(x[0]));}}

在线尝试!

x=>{                                          //Lambda taking in a List<dynamic>
  int c=0,j,t=1,i;                            //A bunch of delcarations jammed together to save bytes
  for(;c++<25;t=c){                           //Loop 24 times (amount of permutations a set of length 4 can have)
    var r="/+*-".ToList();                    //Initialize r as list of operators
    for(i=j=1;j++<4;t=t/j+1)                    //Create the Tth permutation, saving result in r, also reset i to 1
      (r[j-1],r[t%j])=(r[t%j],r[j-1]);
    float k(float z,int p=4) {                //Define local function 'k', with z as current value accumalated and p as current precedence
      char d;int l;float m;                   //Some helper variables
      return i<x.Count                        //If this is not the last number
        &&(l=r.IndexOf(d=x[i][0]))<p?         //  And the current operator's precedence is higher than the current precedence
      k(                                      //  Recursive call with the accumalative value as
        (m=k(x[(i+=2)-1],l))                  //    Another recursive call with the next number following the current operator as seed value,
                                              //    And the next operator's precedence as the precedence value, and store that in variable 'm'
        *0+d<43?z*m:d<44?z+m:d<46?z-m:z/m,    //    And doing the appropriate operation to m and current value ('z')
        p)                                    //  Passing in the current precedence
    :z;                                       //Else just return the current number
    }
    Print(k(x[0]));                           //Print the result of calling k with the first number as starting value
  }
}

我已经修复了它,因此您不必省略重复项,因为它不是所指出的问题的基本部分。
房地美

1
@Arnauld固定以4字节为代价,这是因为我的置换算法有点错误
无知的体现

3

JavaScript(Node.js),132字节

a=>(w=[],F=(b,a)=>b?[...b].map(q=>F(b.replace(q,""),a.replace(eval(`/[\\d.-]+( \\${q} [\\d.-]+)+/g`),eval))):w.push(a))("+-*/",a)&&w

在线尝试!

这允许重复的输出。

的JavaScript(Node.js的)165个 161 155 153 152 137字节

a=>Object.keys((F=(b,a)=>b?[...b].map(q=>F(b.replace(q,""),a.replace(eval(`/[\\d.-]+( \\${q} [\\d.-]+)+/g`),eval))):F[a]=1)("+-*/",a)&&F)

在线尝试!

取一个字符串,在运算符和数字之间使用空格。

a=>                                             // Main function:
 Object.keys(                                   //  Return the keys of the -
  (
   F=(                                          //   Index container (helper function):
    b,                                          //    Operators
    a                                           //    The expression
   )=>
    b                                           //    If there are operators left:
    ?[...b].map(                                //     For each operator:
     q=>
      F(                                        //      Recur the helper function - 
       b.replace(q,""),                         //       With the operator deleted
       a.replace(                               //       And all -
        eval(`/[\\d.-]+( \\${q} [\\d.-]+)+/g`), //        Expressions using the operator
        eval                                    //        Replaced with the evaluated result
       )
      )
    )
    :F[a]=1                                     //     Otherwise - set the result flag.
  )(
   "+-*/",                                      //    Starting with the four operators
   a                                            //    And the expression
  )
  &&F
 )

@JoKing实现了我之前提到的修复程序,[3, -5]现在应该输出。
Shieru Asakoto

2

Perl 6的92个90 88字节

{map {[o](@_)($_)},<* / + ->>>.&{$^a;&{S:g{[\-?<[\d.]>+]+%"$a "}=$/.EVAL}}.permutations}

在线尝试!

在任何运算符之后使用带空格的字符串,并返回一组数字。这主要是通过将所有n op n带有评估结果的实例替换为运算符的所有排列而起作用的。

说明:

{                                                                                   }  # Anonymous code block
                    <* / + ->>>.&{                                    } # Map the operators to:
                                  $^a;&{                             }  # Functions that:
                                        S:g{                }      # Substitute all matches of:
                                            \-?<[\d.]>+]+        # Numbers
                                                         %$a     # Joined by the operator
                                                              =$/.EVAL   # With the match EVAL'd
 map {           },                                                    .permutations   # Map each of the permutations of these operators
      [o](@_)        # Join the functions
             ($_)    # And apply it to the input

您可以删除set,因为消除了消除重复项的条件。好的代码。
房地美

2

Python 3,108字节

f=lambda e,s={*"+-*/"}:[str(eval(p.join(g)))for p in s for g in zip(*map(f,e.split(p),[s-{p}]*len(e)))]or[e]

在线尝试!

该函数将单个字符串作为输入,并返回可能结果的列表。

不打高尔夫球

def get_all_eval_results(expr, operators={*"+-*/"}):
    results = []
    for operator in operators:
        remaining_operators = operators - {operator}

        # Split expression with the current operator and recursively evaluate each subexpression with remaining operators
        sub_expr_results = (get_all_eval_results(sub_expr, remaining_operators) for sub_expr in expr.split(operator))

        for result_group in zip(*sub_expr_results):   # Iterate over each group of subexpression evaluation outcomes
            expr_to_eval = operator.join(result_group)  # Join subexpression outcomes with current operator
            results.append(str(eval(expr_to_eval)))   # Evaluate and append outcome to result list of expr
    return results or [expr]  # If results is empty (no operators), return [expr]

在线尝试!


1

果冻,30个字节

œṡ⁹¹jṪḢƭ€jŒVɗßʋFL’$?
Ḋm2QŒ!烀

在线尝试!

一对链接。第二个是主链接,并以散点图/整数的Jelly列表作为参数,并散布着运算符作为字符。这是Jelly在带有命令行参数的完整程序中运行时采用其输入方式的扁平化版本。链接的返回值是单个成员列表的列表,每个成员列表都是表达式的可能值。

说明

助手链接

将以运算符(作为字符)交替的浮点数/整数列表作为左参数,将运算符作为字符作为右参数;评估由相关运算符分隔的数字后,从左到右返回返回输入列表。

œṡ⁹                  | Split once by the right argument (the operator currently being processed)
                   ? | If:
                  $  | - Following as a monad
                L    |   - Length
                 ’   |   - Decremented by 1
              ʋ      | Then, following as a dyad:
   ¹                 | - Identity function (used because of Jelly’s ordering of dyadic links at the start of a dyadic chain)
    j       ɗ        | - Join with the following as a dyad, using the original left and right arguments for this chain:
     ṪḢƭ€            |   - Tail of first item (popping from list) and head from second item (again popping from list); extracts the numbers that were either side of the operator, while removing them from the split list
         j           |   - Joined with the operator
          ŒV         |   - Evaluate as Python (rather than V because of Jelly’s handling of decimals with a leading zero)
            ß        | - Recursive call to this helper link (in case there are further of the same operator)
               F     | Else: Flatten

主链接

获取与运算符交替的浮点/整数列表(作为字符)

Ḋ         | Remove first item (which will be a number)
 m2       | Every 2nd item, starting with the first (i.e. the operators)
   Q      | Uniquify
    Œ!    | Permutations
      烀 | For each permuted list of operators, reduce using the helper link and with the input list as the starting point

1

Python 2中182个 172字节

import re
def f(s,P=set('+-/*')):
 S=[eval(s)]
 for p in P:
	t=s
	while p+' 'in t:t=re.sub(r'[-\d.]+ \%s [-\d.]+'%p,lambda m:`eval(m.group())`,t,1)
	S+=f(t,P-{p})
 return S

在线尝试!

按照“对于隐式分析类型的语言,浮点数可以替换浮点数”,以整数形式输入输入。


1

朱莉娅 1.2,88(82)字节

f(t)=get(t,(),[f.([t[1:i-1];t[i+1](t[i],t[i+2]);t[i+3:end]] for i=1:2:length(t)-2)...;])
julia> f([2, +, 3, *, 4])
2-element Array{Int64,1}:
 20
 14

julia> f([18, /, 3, *, 2, -, 1])
6-element Array{Float64,1}:
 11.0
  6.0
  2.0
  3.6
  6.0
  6.0

以数字和中缀函数向量的形式获取磁带,评估每个单个函数调用,然后将每个结果磁带递归传递给它自己,直到只剩下一个数字为止。不幸的是,get(t, (), ...)在Julia 1.0中无法正常工作,因此需要更新的版本。

如果可接受一堆嵌套数组作为输出,则可以节省六个字节:

f(t)=get(t,(),f.([t[1:i-1];t[i+1](t[i],t[i+2]);t[i+3:end]] for i=1:2:length(t)-2))

输出:

julia> f([18, /, 3, *, 2, -, 1])
3-element Array{Array{Array{Float64,1},1},1}:
 [[11.0], [6.0]]
 [[2.0], [3.6]] 
 [[6.0], [6.0]] 

0

Perl 5(-alp),89个字节

my$x;map{$x.=$`.(eval$&.$1).$2.$"while/\d+[-+*\/](?=(\d+)(.*))/g}@F;$_=$x;/[-+*\/]/&&redo

蒂奥

或唯一值,99字节

my%H;map{$H{$`.(eval$&.$1).$2}++while/\d+[-+*\/](?=(\d+)(.*))/g}@F;$_=join$",keys%H;/[-+*\/]/&&redo
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.