Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
Fórmula matemática Ruby de cadena con 'x'

Para no oxidarme quiero refrescar mis conocimientos de rubí puro resolviendo algunos algoritmos. No puedo resolver un algoritmo más grande sin resolver uno más pequeño como el siguiente ejemplo.

Haga que la función falta_dígito(str) tome el parámetro str , que será una fórmula matemática simple con tres números, un solo operador (+, -, *, or /) y un signo igual (=) y devuelva el dígito que completa el ecuación. En uno de los números de la ecuación, habrá un carácter x , y su programa debe determinar qué dígito falta. Por ejemplo, si str es "3x + 12 = 46" , entonces su programa debería generar 4 .

 Examples Input: "4 - 2 = x" Output: 2 Input: "1x0 * 12 = 1200" Output: 0

Creo que encontré la solución para python pero no puedo encontrar el código Ruby correspondiente en ninguna parte.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Python y Ruby son bastante similares, aunque intentar convertir esto sin un TDD básico hubiera sido difícil. Aquí está el archivo convertido a Ruby de su ejemplo de python. Refactorizaría este código, pero las pruebas simples aquí pasan, las que se dan en su ejemplo vinculado.

string_math_x.rb

 class StringMathX def self.calculate(str) exp = str.split() first_operand = exp[0] operator = exp[1] second_operand = exp[2] resultant = exp[-1] # If x is present in resultant if resultant[/x/] first_operand = first_operand.to_i second_operand = second_operand.to_i if operator == '+' res = first_operand + second_operand elsif operator == '-' res = first_operand - second_operand elsif operator == '*' res = first_operand * second_operand else res = first_operand / second_operand end return res end # If x in present in operands # If x in the first operand if first_operand == 'x' x = first_operand.to_i second_operand = second_operand.to_i if operator == '+' res = resultant - second_operand elsif operator == '-' res = resultant + second_operand elsif operator == '*' res = resultant / second_operand else res = resultant / second_operand end # If x is in the second operand else x = second_operand.to_i first_operand = first_operand.to_i if operator == '+' res = resultant-first_operand elsif operator == '-' res = first_operand - second_operand elsif operator == '*' res = resultant.to_i / first_operand.to_i else res = first_operand.to_i / resultant.to_i end end res = res.to_s k = 0 for i in [*0..x] if i == x result = res[k] break else k += 1 end end result.to_i end end

./prueba/prueba.rb

 require 'minitest/autorun' require_relative '../lib/string_math_x' class StringMathXTest < Minitest::Test def test_basic_subtration input = '4 - 2 = x' assert(StringMathX.calculate(input) == 2, 'outputs 2') end def test_whats_up_returns_doc input = '1x0 * 12 = 1200' assert(StringMathX.calculate(input) == 0, 'outputs 0') end end

Para ejecutar esto, es posible que necesite gem install minitest

Luego ejecute ruby test/test.rb

over 4 years ago · Santiago Trujillo Report

0

def findx(str) s = str.sub('=', '==') i = s.index('x') pre = s[0,i] post = s[i+1..-1] ('0'..'9').find { |d| eval(pre+d+post) rescue nil }&.to_i end
 findx("4 - 2 = x") #=> 2 findx("1x0 * 12 = 1200") #=> 0 findx("3**x = 81") #=> 4 findx("1/x == 2.0").nil? #=> true

se necesita rescue nil en caso de que se realice una división por cero. & es el operador de puerto seguro . Devuelve nil , sin tener en cuenta todo lo que sigue, si la parte anterior devuelve nil .

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!