Start learning free

LESSON 89 OF 414 · CONDITIONAL STATEMENTS - CHALLENGES

Absolute Difference in Rust: Comparing Two Numbers

Practice Read the full explanation

The absolute difference is a measure of the difference between two numbers but expressed as a positive number.

In other words, it’s taking the difference between two values (x - y) and then calculating the absolute value of the result.

Create a function (called as absDiff in the examples below; use the name from the starter code) that takes in two numbers a and b and returns their absolute difference.

Examples:

absDiff(3, 0) ➞ 3

absDiff(0, 3) ➞ 3

absDiff(10, -1) ➞ 11

absDiff(-5, -7) ➞ 2

absDiff(6, -6) ➞ 12

absDiff(7, 7) ➞ 0

Note:

Do not use the absolute value function provided by Rust (it will defeat the purpose of the challenge)


Hints:


If a is less than b, the absolute difference equals b - a. What if a is greater than or equal to b?

If a < b, we should return b - a. Otherwise, we should return a - b. We can use an if statement to put this in code.
STEP 1 OF 3
    Ctrl + Enter to check

    RUST · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Absolute Difference in Rust, explained

    Problem overview

    The function abs_diff takes two i32 values, a and b, and returns the distance between them on the number line. That is a - b or b - a, whichever is not negative. The order of the arguments doesn't matter: abs_diff(3, 0) and abs_diff(0, 3) are both 3.

    Worked examples: abs_diff(10, -1) is 11, abs_diff(-5, -7) is 2 and abs_diff(6, -6) is 12. The lesson asks you to write this with a comparison instead of calling the library's absolute-value function.

    Approach

    Subtracting the smaller number from the larger one always gives a result that is zero or positive. So find out which of the two is smaller and subtract in that order. If a is less than b, the answer is b - a. Otherwise a is greater than or equal to b, and the answer is a - b. When the numbers are equal, either order gives 0.

    Trace abs_diff(-5, -7). Here a is -5 and b is -7. Since -5 is not less than -7, the if is skipped and the function returns -5 - (-7), which is 2. Now swap the arguments: abs_diff(-7, -5) takes the if branch and returns -5 - (-7) as well. Both orders end in the same subtraction, with the larger number first.

    The absolute difference is the absolute value of a - b, and the comparison does the sign-flipping work that an abs function would otherwise do.

    Step by step

    1. Compare the inputs. Write an if with the condition a < b. Rust doesn't need parentheses around it, but the braces are required.
    2. Handle the case where a is smaller. Inside the if, return b - a;. Subtracting the smaller number from the larger one can't be negative.
    3. Handle the rest below the if. Add return a - b; after it. No else is needed: when a < b is true the function has already returned, so this line only runs when a is greater than or equal to b.

    The solution in Rust

    impl Solution {
        fn abs_diff(a: i32, b: i32) -> i32 {
            if a < b {
                return b - a;
            }
            return a - b;
        }
    }
    

    Rust details worth knowing:

    • Early return replaces else. A return ends the function immediately, so code after an if that returns only runs when the condition was false. The lines read as "if a is smaller do this, otherwise do that" without the extra block.
    • The same logic as an expression. Since if/else produces a value in Rust, the body can also be if a < b { b - a } else { a - b } with no return and no semicolon.
    • A built-in exists. Integer types have an abs_diff method, as in 7i32.abs_diff(-3), which gives 10. For i32 it returns a u32, so it avoids the overflow described below. The lesson's function is an associated function of Solution, called as Solution::abs_diff(a, b), so the two don't conflict.
    • Same type in and out. The parameters and the result are all i32, so Rust does no conversion between them.

    Edge cases and common mistakes

    • Equal numbers. With a == b the condition is false and the function returns a - b, which is 0. Using a <= b instead would also work.
    • Negative inputs. abs_diff(-5, -7) compares -5 < -7, which is false, and returns -5 - (-7), which is 2. Subtracting a negative number adds its size.
    • Subtracting in a fixed order. Always returning a - b gives -3 for abs_diff(0, 3). The comparison is what keeps the result non-negative.
    • Overflow. The difference of two i32 values can be larger than an i32 can hold. In the optimized build the lessons use, abs_diff(i32::MAX, -1) wraps silently and returns -2147483648. A debug build panics on the same subtraction. Ordinary inputs stay far from the limit.
    • Missing return. If the last line of the function is a - b; with a semicolon, the function ends without a value and the compiler reports mismatched types. Write return a - b;, or drop the semicolon to make it the final expression.

    Testing

    • a = 3, b = 0 gives 3.
    • a = 0, b = 3 gives 3.
    • a = 10, b = -1 gives 11.
    • a = -5, b = -7 gives 2.
    • a = 6, b = -6 gives 12.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free