不等式の連鎖を評価する


17

不等式のチェーンが真であるか偽であるかを評価するコードを記述します。入力例は文字列です

3<=4!=9>3==3

各コンポーネントが真であるため、これは真実です。

(3<=4) and (4!=9) and (9>3) and (3==3)

入力:

1つ以上の不等式のチェーンを表す文字列。許可される比較演算子は

==   equals
!=   does not equal
>    is greater than
>=   is greater than or equal to
<    is less than
<=   is less than or equal to

許可される数字は一桁の数字です0通過9。スペース、括弧、その他の記号はありません。

出力:

一貫したTruthyまたはFalseyの値としての不平等の正しさ。一貫性とは、すべてのTruthy出力が同じであり、すべてのFalsey出力が同じであることを意味します。

制限:

この課題の目的は、不平等を処理するコードを作成することです。不平等は、チェーン内の単一の不平等であっても、それらをコードとして評価することではありません。そのため、Pythonのような方法eval及びexecその評価または実行コードが禁止されています。文字列として名前が指定されたメソッドまたは演算子を検索する関数も同様です。また、評価を行うためのプロセスやプログラムを起動することも許可されていません。

テストケース:

3<=4!=9>3==3
True

3<=4!=4
False

5>5
False

8==8<9>0!=2>=1
True

<=や> =の代わりに≤や≥のようなUnicode不等号を使用して入力を受け入れることはできますか?
FUZxxl

@FUZxxlできません。
xnor

回答:


7

ルビー、71 + 1 = 72

コマンドラインフラグを使用して-n、実行

p (0..99).none?{|i|~/#{a=i%10}(#{%w/!=|. <?=* >?=*/[a<=>b=i/10]})#{b}/}

失敗する可能性があるすべての正規表現を生成し、入力文字列がそれらのいずれかに一致するかどうかをチェックします。trueそうでない場合は出力し、そうでない場合は出力しますfalse。改行で区切られたSTDINを介して入力を受け取ります。

トリック:

  • 0から99までループし、10桁と1桁を抽出することで、可能なすべての桁のペアを取得します。
  • 実際に行う唯一の比較はa<=>b、より小さい、等しい、または大きい場合に-1、0、または1を返します。これらはすべて3文字列配列の異なる要素にスライスされ、一致しない比較の正規表現を見つけます。

なんて賢い戦略でしょう!
xnor

6

Perl、82

$_=<>;($'<=>$&)-61+ord$1&&($2&&$&==$')^('$'lt$1)&&die"\n"while/\d(.)(=?)/g;print 1

空の文字列はPerlのメインのfalsey値であるため、trueの場合は1、falseの場合は空白行を出力します。

whileループは、正規表現に一致する文字列を調べ\d(.)(=?)ます。次に、変数$1$2は演算子の文字に対応し、特殊変数$&$'は数値コンテキストで2つのオペランドとして動作します。オペランドが比較され<=>、結果が演算子の最初の文字と照合されます。次に、平等と不平等が特別に扱われます。


4

CJam、60バイト

このコードは少し見苦しく、潜在的に完全に最適化されていない可能性がありますが、これまでのところ最高です。

オンラインでお試しください。

q_A,sSer_S%@@-(])1\@z{~:X\:^i['=")<"P"(>"P'<'^'>PPP]=~e&X}/;

説明

q               "Read the input";
_A,sSer         "Copy the input and replace each digit with a space";
_S%             "Split around spaces to obtain the operation list";
@@-             "Remove operations from the input to obtain the operand list";
(])1\@z         "Remove the first operand from the list to be the initial left
                 operand, initialize the result to 1 (true), and pair up the
                 operations and remaining operands";
{               "For each operation-operand pair:";
  ~:X             "Let the operand be the right operand of this operation";
  \:^i            "Hash the operation (bitwise XOR of all characters)";
  [               "Begin cases:";
    '=              " 0: Equals";
    ")<"            " 1: Less than or equal to";
    P               " 2: (Invalid)";
    "(>"            " 3: Greater than or equal to";
    P               " 4: (Invalid)";
    '<              " 5: Less than";
    '^              " 6: Bitwise XOR (stand-in for not equal to)";
    '>              " 7: Greater than";
    P               " 8: (Invalid)";
    P               " 9: (Invalid)";
    P               "10: (Invalid)";
  ]=~             "Execute the case selected by the operation hash modulo 11";
  e&              "Compute the logical AND of the result and the value produced
                   by this operation to be the new result";
  X               "Let the right operand be the new left operand";
}/              "End for each";
;               "Clean up and implicitly print result";

4

JavaScript(ES6)110 116

簡単:スキャン文字列、cは現在の数字、lは最後の数字、oは演算子です。

F=x=>(l='',[for(c of x)10-c?(v=!l||v&&(o<'<'?l!=c:(o[1]&&c==l)||(o<'='?l<c:o<'>'?c==l:l>c)),l=c,o=''):o+=c],v)

Firefox / FireBugコンソールでテストする

;['3<=4!=9>3==3','3<=4!=4','5>5','8==8<9>0!=2>=1']
.forEach(s=>console.log(s,F(s)))

3 <= 4!= 9> 3 == 3 true
3 <= 4!= 4 false
5> 5 false
8 == 8 <9> 0!= 2> = 1 true


3

Haskell、156バイト

r a=read[a]::Int
l"!"=(/=)
l"="=(==)
l">"=(>=)
l"<"=(<=)
k">"=(>)
k"<"=(<)
[]#_=1<2
(a:'=':b:c)#i=l[a]i(r b)&&c#r b
(a:b:c)#i=k[a]i(r b)&&c#r b
f(h:t)=t#r h

使用例:

f "3<=4!=9>3==3"        -> True
f "3<=4!=4"             -> False
f "5>5"                 -> False
f "8==8<9>0!=2>=1"      -> True

ゴルフされていないバージョン:

digitToInt d = read [d] :: Int

lookup2 "!" = (/=)
lookup2 "=" = (==)
lookup2 ">" = (>=)
lookup2 "<" = (<=)

lookup1 ">" = (>)
lookup1 "<" = (<)

eval []              _ = True
eval (op:'=':d:rest) i = lookup2 [op] i (digitToInt d) && eval rest (digitToInt d)
eval (op:d:rest)     i = lookup1 [op] i (digitToInt d) && eval rest (digitToInt d)

evalChain (hd:rest) = eval rest (digitToInt hd)

eval2つの引数を取ります:解析する文字列(常に比較演算子で始まる)と、i比較のための左引数である(前のラウンドで右引数だった)数値。オペレータは、によって返されるlookup2(第二が常にあるので、チェックのみ第一のchar、それは2つの文字のオペレータの場合=)とすることによってlookup1、それは単に1つの文字だ場合。eval自身を再帰的に呼び出し、すべての戻り値を論理値andに結合します&&


3

Common Lisp- 300 185 169 165

(lambda(s)(loop for(a o b)on(mapcar'read-from-string(cdr(ppcre:split"([0-9]+)"s :with-registers-p t)))by #'cddr always(if o(funcall(case o(=='=)(!='/=)(t o))a b)t)))

(mapcar (lambda(s) ...)
       '("2<=3<=6>2<10!=3"
         "3<=4!=9>3==3" 
         "3<=4!=4" 
         "5>5"
         "8==8<9>0!=2>=1"))
=> (T T NIL NIL T)

説明

(lambda (s)
  (loop for (a o b) on (mapcar
                        'read-from-string
                        (cdr
                         (cl-ppcre:split "([0-9]+)" s
                                         :with-registers-p t))) by #'cddr
        always (if o
                   (funcall (case o
                                  (== '=)
                                  (!= '/=)
                                  (t o))
                            a b)
                   t)))
  • ppcre:split数字で分割します。例えば:

    (ppcre:split "([0-9]+)" "2<=3<=6>2<10!=3" :with-registers-p t)
    => ("" "2" "<=" "3" "<=" "6" ">" "2" "<" "10" "!=" "3")
    

    最初の空の文字列に注意してください。 cdr

  • read-from-stringこのリストへのマッピングは、read各文字列に対して関数を呼び出し、シンボルと数値を返します。

  • loop for (a op b) on '(3 < 5 > 2) by #'cddrステップリストを反復処理2及び従って結合aop及びb連続する各パスについて、以下、。

    a  op  b
    ----------
    3  <    5
    5  >    2
    2  nil  nil
    
  • always次の式が常に真であるかどうかを確認します。演算子がnil上記のとおりであるか(上記を参照)、比較の結果が保持されます(下記を参照)。

  • case選択コモンLispの比較機能、以前に読み取られたシンボルに係ります。一部の演算子はLispと指定された言語で同一oであるため、デフォルトの場合に単純に返すことができます。


1

Python 2、95 102

t=1
n=o=3
for c in map(ord,raw_input()):
 o+=c
 if 47<c<58:t&=627>>(o-c+3*cmp(n,c))%13;n=c;o=0
print t

ループは、文字列を一度に1文字ずつ単純にパススルーします。t&=...マジックが起こるところ部分があります。基本的に、演算子は、値がcmp(lhs,rhs)(-1、0、または1であるかどうかに応じて、lhsより小さい、等しい、または大きいrhs)と共にハッシュします。結果は、その演算子が与えられた数値が適切に比較されるかどうかに応じて0または1を与えるルックアップテーブルへのキーです。どのルックアップテーブルですか?数値627 =0001001110011バイナリのです。ビット単位演算子が残りを行います。

これは、指定された4つのテストケースで機能します。別のケースでエラーが見つかった場合はお知らせください。私はそれをあまり厳密にテストしていません。


a入力として取り込む必要があります。
xnor

@xnorおっと。修正しました。
DLosc

1

Javascript 101バイト

ここに投稿されたjsソリューションとは異なるアプローチ

F=(s,i=0,l=o="")=>[...s].every(c=>c>=0?[l^c,l==c,,l<c,l>c,l<=c,,l>=c]["!==<><=>=".search(o,l=c,o="")]:o+=c,l=o="")

console.log(F("3<=4!=9>3==3")==true)
console.log(F("3<=4!=4")==false)
console.log(F("5>5")==false)
console.log(F("8==8<9>0!=2>=1")==true)


0

Java 8、283バイト

s->{String[]a=s.split("\\d"),b=s.split("\\D+");int i=0,r=1,x,y;for(;i<a.length-1;)if((x=new Byte(b[i]))!=(y=new Byte(b[++i]))&(a[i].equals("=="))|(a[i].equals("!=")&x==y)|(a[i].equals(">")&x<=y)|(a[i].equals(">=")&x<y)|(a[i].equals("<")&x>=y)|(a[i].equals("<=")&x>y))r--;return r>0;}

説明:

ここで試してみてください。

s->{                            // Method with String parameter and boolean return-type
  String[]a=s.split("\\d"),     //  All the inequalities
          b=s.split("\\D+");    //  All the digits
  int i=0,                      //  Index-integer (starting at 0)
      r=1,                      //  Flag integer for the result, starting at 1
      x,y;                      //  Temp integer `x` and `y`
  for(;i<a.length-1;)           //  Loop from 0 to the length - 1
  if((x=new Byte(b[i]))!=(y=new Byte(b[++i]))&(a[i].equals("=="))
                                //   If "==" and `x` and `y` as int are not equal:
     |(a[i].equals("!=")&x==y)  //   Or "!=" and `x` and `y` are equal
     |(a[i].equals(">")&x<=y)   //   Or ">" and `x` is smaller or equal to `y`
     |(a[i].equals(">=")&x<y)   //   Or ">=" and `x` is smaller than `y`
     |(a[i].equals("<")&x>=y)   //   Or "<" and `x` is larger or equal to `y`
     |(a[i].equals("<=")&x>y))  //   Or "<=" and `x` is larger than `y`
    r--;                        //    Decrease `r` by 1
                                //  End of loop (implicit / single-line body)
  return r>0;                   //  Return if `r` is still 1
}                               // End of method
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.