Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move find_intermediate to the server crate #580

Open
uonr opened this issue Aug 25, 2024 · 0 comments
Open

Move find_intermediate to the server crate #580

uonr opened this issue Aug 25, 2024 · 0 comments

Comments

@uonr
Copy link
Collaborator

uonr commented Aug 25, 2024

https://wiki.postgresql.org/wiki/User-specified_ordering_with_fractions

Translate by Claude

use std::cmp::Ordering;

/// Find an intermediate fraction between p1/q1 and p2/q2.
///
/// The fraction chosen is the highest fraction in the Stern-Brocot
/// tree which falls strictly between the specified values.
///
/// Inputs must not be null (caller's responsibility), but the value
/// p2=1 q2=0 is allowed for the upper bound without causing any
/// division by zero errors.
fn find_intermediate(p1: i32, q1: i32, p2: i32, q2: i32) -> (i32, i32) {
    let mut pl = 0;
    let mut ql = 1;
    let mut ph = 1;
    let mut qh = 0;

    if (p1 as i64 * q2 as i64 + 1) != (p2 as i64 * q1 as i64) {
        loop {
            let p = pl + ph;
            let q = ql + qh;

            match ((p as i64 * q1 as i64).cmp(&(q as i64 * p1 as i64)), 
                   (p2 as i64 * q as i64).cmp(&(q2 as i64 * p as i64))) {
                (Ordering::Less | Ordering::Equal, _) => {
                    pl = p;
                    ql = q;
                }
                (_, Ordering::Less | Ordering::Equal) => {
                    ph = p;
                    qh = q;
                }
                _ => return (p, q),
            }
        }
    } else {
        (p1 + p2, q1 + q2)
    }
}

fn main() {
    let (p, q) = find_intermediate(1, 3, 2, 5);
    println!("Intermediate fraction: {}/{}", p, q);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant