use crate::{Error, Outcome, plugins::integer_queries, re};
use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};
fn invalid() -> Error {
Error("invalid_expression".into())
}
pub(super) fn rewrite(input: &str) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
if let Some(c) = re!(r"(?i)^a machine processes (.+?) parts? in (.+?) hours?; calculate its rate in parts per hour and the time in minutes to process (.+?) parts? at that constant rate$").captures(input) {
return Some(Ok(format!("wording_machine_rate({};{};{})", &c[1], &c[2], &c[3])));
}
if let Some(c) = re!(r"(?i)^a vehicle travels (.+?) km in (.+?) hours? (.+?) minutes, then (.+?) km in (.+?) minutes; calculate total distance, total elapsed time in hours, and overall average speed in km/h$").captures(input) {
return Some(Ok(format!("wording_trip_average({};{};{};{};{})", &c[1], &c[2], &c[3], &c[4], &c[5])));
}
if let Some(c) = re!(r"(?i)^what is the least common multiple of (.+) and (.+), and what is their greatest common divisor$").captures(input) {
return Some(Ok(format!("wording_counts({};{})", &c[1], &c[2])));
}
if let Some(c) = re!(r"(?i)^simplify the ratio (.+):(.+) to whole numbers, then tell me the difference between the two terms$").captures(input) {
return Some(Ok(format!("wording_ratio({};{})", &c[1], &c[2])));
}
if let Some(c) = re!(r"(?i)^a test has (.+) questions; each correct answer is worth (.+) points and each wrong answer loses (.+) points?\. what score results from (.+) correct and (.+) wrong$").captures(input) {
return Some(Ok(format!("wording_score({};{};{};{};{})", &c[1], &c[2], &c[3], &c[4], &c[5])));
}
if re!(r"(?i)^a test has .+ questions;").is_match(input) {
return Some(Err(invalid()));
}
None
}
fn arguments<'a>(input: &'a str, name: &str, count: usize) -> Result<Vec<&'a str>, Error> {
let inner = input
.strip_prefix(name)
.and_then(|s| s.strip_prefix('('))
.and_then(|s| s.strip_suffix(')'))
.ok_or_else(invalid)?;
let values: Vec<_> = inner.split(';').map(str::trim).collect();
if values.len() != count || values.iter().any(|s| s.is_empty()) {
return Err(invalid());
}
Ok(values)
}
fn scalar(input: &str) -> Result<BigRational, Error> {
let (n, d) = integer_queries::ratio_value(input).map_err(|error| {
if error.0 == "invalid_integer_expression" {
invalid()
} else {
error
}
})?;
Ok(BigRational::new(n, d))
}
fn bounded(value: BigRational) -> Result<BigRational, Error> {
if value.numer().bits().max(value.denom().bits()) > 1_000_000 {
return Err(Error("integer_limit".into()));
}
Ok(value)
}
fn positive(input: &str) -> Result<BigRational, Error> {
let value = scalar(input)?;
if value <= BigRational::zero() {
return Err(Error("invalid_physical_quantity".into()));
}
bounded(value)
}
fn nonnegative(input: &str) -> Result<BigRational, Error> {
let value = scalar(input)?;
if value.is_negative() {
return Err(Error("invalid_physical_quantity".into()));
}
bounded(value)
}
fn decimal(value: &BigRational) -> Result<String, Error> {
if value.is_integer() {
return Ok(integer_queries::decimal(&value.to_integer()));
}
let converted = value
.to_f64()
.filter(|v| v.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if converted == 0.0 && !value.is_zero() {
return Err(Error("numeric_underflow".into()));
}
Ok(crate::number(converted))
}
fn count(input: &str) -> Result<BigInt, Error> {
let value = scalar(input)?;
if !value.is_integer() {
return Err(Error("integer_required".into()));
}
if value.is_negative() {
return Err(Error("invalid_integer_argument".into()));
}
Ok(value.to_integer())
}
pub(super) fn evaluate(input: &str) -> Outcome {
let input = crate::plugins::syntax::ungroup(input);
if input.starts_with("wording_machine_rate(") {
return Some((|| {
let args = arguments(input, "wording_machine_rate", 3)?;
let parts = positive(args[0])?;
let hours = positive(args[1])?;
let target = nonnegative(args[2])?;
let rate = bounded(parts / hours)?;
let minutes = bounded(target / &rate * BigRational::from_integer(60.into()))?;
Ok(format!(
"rate: {} parts/hour; time: {} min",
decimal(&rate)?,
decimal(&minutes)?
))
})());
}
if input.starts_with("wording_trip_average(") {
return Some((|| {
let args = arguments(input, "wording_trip_average", 5)?;
let first_distance = positive(args[0])?;
let hours = nonnegative(args[1])?;
let first_minutes = nonnegative(args[2])?;
let second_distance = positive(args[3])?;
let second_minutes = positive(args[4])?;
let sixty = BigRational::from_integer(60.into());
let distance = bounded(first_distance + second_distance)?;
let first_elapsed = bounded(hours + first_minutes / &sixty)?;
if first_elapsed.is_zero() {
return Err(Error("invalid_physical_quantity".into()));
}
let elapsed = bounded(first_elapsed + second_minutes / sixty)?;
let speed = bounded(&distance / &elapsed)?;
Ok(format!(
"total distance: {} km; total elapsed time: {} h; average speed: {} km/h",
decimal(&distance)?,
decimal(&elapsed)?,
decimal(&speed)?
))
})());
}
if input.starts_with("wording_counts(") {
return Some((|| {
let args = arguments(input, "wording_counts", 2)?;
let a = integer_queries::value(args[0])?;
let b = integer_queries::value(args[1])?;
let lcm = integer_queries::value(&format!("lcm({a},{b})"))?;
let gcd = integer_queries::value(&format!("gcd({a},{b})"))?;
Ok(format!(
"least common multiple: {lcm}; greatest common divisor: {gcd}"
))
})());
}
if input.starts_with("wording_ratio(") {
return Some((|| {
let args = arguments(input, "wording_ratio", 2)?;
let (a, b) = (scalar(args[0])?, scalar(args[1])?);
if b.is_zero() {
return Err(Error("division_by_zero".into()));
}
let ratio = bounded(a / b)?;
Ok(format!(
"ratio: {}:{}; difference: {}",
ratio.numer(),
ratio.denom(),
ratio.numer() - ratio.denom()
))
})());
}
if input.starts_with("wording_score(") {
return Some((|| {
let args = arguments(input, "wording_score", 5)?;
let (total, correct, wrong) = (count(args[0])?, count(args[3])?, count(args[4])?);
let (worth, penalty) = (scalar(args[1])?, scalar(args[2])?);
if worth.is_negative() || penalty.is_negative() {
return Err(Error("invalid_integer_argument".into()));
}
if correct.clone() + &wrong != total {
return Err(Error("inconsistent_count".into()));
}
let score = bounded(
bounded(BigRational::from_integer(correct) * worth)?
- bounded(BigRational::from_integer(wrong) * penalty)?,
)?;
Ok(format!("{score} points"))
})());
}
None
}