Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h2>Ruby</h2> <p><strong>Number of characters: <del>217</del> 179</strong></p> <p><del>This is the shortest ruby solution up to now (one heavily based on RegExp yields incorrect answers when string contains few groups of parenthesis)</del> -- no longer true. Solutions based on regex and substitution are shorter. This one is based on stack of accumulators and parses whole expression from left to right. It is re-entrant, and does not modify input string. It could be accused of breaking the rules of not using <code>eval</code>, as it calls <code>Float</code>'s methods with identical names as their mathematical mnemonics (+,-,/,*).</p> <p>Obfuscated code <em>(old version, tweaked below)</em>:</p> <pre><code>def f(p);a,o=[0],['+'] p.sub(/-/,'+-').scan(/(?:(-?\d+(?:\.\d+)?)|(.))\s*/).each{|n| q,w=n;case w;when'(';a&lt;&lt;0;o&lt;&lt;'+';when')';q=a.pop;else;o&lt;&lt;w end if q.nil?;a[-1]=a[-1].method(o.pop).call(q.to_f) if !q.nil?};a[0];end </code></pre> <p>More obfuscated code:</p> <pre><code>def f(p);a,o=[0],[:+] p.scan(/(?:(-?\d+(?:\.\d+)?)|(.))\s*/).each{|n|q,w=n;case w when'(';a&lt;&lt;0;o&lt;&lt;:+;when')';q=a.pop;else;o&lt;&lt;w;end if !q a&lt;&lt;a.pop.send(o.pop,q.to_f)if q};a[0];end </code></pre> <p>Clean code:</p> <pre><code>def f(p) accumulators, operands = [0], ['+'] p.gsub(/-/,'+-').scan(/(?:(-?\d+(?:\.\d+)?)|(.))\s*/).each do |n| number, operand = n case operand when '(' accumulators &lt;&lt; 0 operands &lt;&lt; '+' when ')' number = accumulators.pop operands.pop else operands[-1] = operand end if number.nil? accumulators[-1] = accumulators.last.method(operands[-1]).call(number.to_f) unless number.nil? end accumulators.first end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload