Skip to content

Instantly share code, notes, and snippets.

@FreeFull
Created December 23, 2014 23:30
Show Gist options
  • Select an option

  • Save FreeFull/d915153967474bb9aab0 to your computer and use it in GitHub Desktop.

Select an option

Save FreeFull/d915153967474bb9aab0 to your computer and use it in GitHub Desktop.
fn naive_int_abs_diff(x: int, y: int) -> uint {
use std::num::SignedInt;
(x - y).abs() as uint
}
fn naive_uint_abs_diff(x: uint, y: uint) -> uint {
naive_int_abs_diff(x as int, y as int)
}
fn uint_abs_diff(x: uint, y: uint) -> uint {
if x > y {
x - y
} else {
y - x
}
}
fn int_abs_diff(x: int, y: int) -> uint {
use std::int::MIN;
let x = (x - MIN) as uint;
let y = (y - MIN) as uint;
uint_abs_diff(x, y)
}
fn main() {
use std::{int, uint};
let (x, y) = (int::MIN, int::MAX);
// The naive subtraction results in the value 1, while the correct result is uint::MAX
println!("naive int abs diff: {}, correct int abs diff: {}", naive_int_abs_diff(x, y), int_abs_diff(x, y));
// Exact same problem, except with unsigned integer inputs.
let (x, y) = (0, uint::MAX);
println!("naive uint abs diff: {}, correct uint abs diff: {}", naive_uint_abs_diff(x, y), uint_abs_diff(x, y));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment