bench-rejected-impls/18_operation_order.rb
# Couldn't use the stack-based solution for part 2,
# so used string replacement one instead.
# And then I went back and made one for part 1 too.
Couldn't use the stack-based solution for part 2,
so used string replacement one instead.
And then I went back and made one for part 1 too.
Couldn ' t use the stack - based solution for part 2 so used string replacement one instead . And then I went back and made one for part 1 too .
def string_replacement_ltr(expr, depth = 0, verbose: false)
  expr = expr.delete(' ') if depth == 0
  lpad = '    ' * depth
  while (rparen = expr.index(?)))
    lparen = expr.rindex(?(, rparen)
    replace = expr[(lparen + 1)...rparen]
    replacement = string_replacement_ltr(replace, depth + 1, verbose: verbose)
    expr[lparen..rparen] = replacement.to_s
    puts "#{lpad}#{replace} = #{replacement}, now #{expr}" if verbose
  end
  while (add_or_mul = expr[/(\d+)(\+|\*)(\d+)/])
    expr[add_or_mul] = v = Integer($1).send($2, Integer($3)).to_s
    puts "#{lpad}#$1 #$2 #$3 = #{v}; now #{expr}" if verbose
  end
  Integer(expr)
end
def string_replacement_ltr ( expr , depth = 0 , verbose : false ) expr = expr . delete ( ' ' ) if depth == 0 lpad = '    ' * depth while ( rparen = expr . index ( ?) ) ) lparen = expr . rindex ( ?( , rparen ) replace = expr [ ( lparen + 1 ) ... rparen ] replacement = string_replacement_ltr ( replace , depth + 1 , verbose : verbose ) expr [ lparen .. rparen ] = replacement . to_s puts "#{lpad}#{replace} = #{replacement}, now #{expr}" if verbose end while ( add_or_mul = expr [ / ( \d +)( \+ | \* )( \d +) / ] ) expr [ add_or_mul ] = v = Integer ( $1 ) . send ( $2 , Integer ( $3 ) ) . to_s puts "#{lpad}#$1 #$2 #$3 = #{v}; now #{expr}" if verbose end Integer ( expr ) end
Couldn't use the stack-based solution for part 2,
so used string replacement one instead.
Couldn ' t use the stack - based solution for part 2 so used string replacement one instead .
# Looking forward from the first left parenthesis is prone to nesting problems like ((1 + 2) + 3) # Looking backward from the first right parenthesis, though, is totally fine.
expr
<not_specific>
depth
<not_specific>
verbose
<not_specific>