Skip to content

Commit

Permalink
refactor less likely to overflow
Browse files Browse the repository at this point in the history
  • Loading branch information
michirakara committed Sep 30, 2024
1 parent e3dbd28 commit a2be93a
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 0 deletions.
82 changes: 82 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ version = "0.1.0"
edition = "2021"

[dependencies]
num = "0.4.3"
41 changes: 41 additions & 0 deletions src/algorithm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use num::traits::{FromPrimitive, Num};

pub fn binary_search_threshold<T, F>(mut ok: T, mut ng: T, mut check: F, threshold: T) -> T
where
T: Num + PartialOrd + FromPrimitive + Copy,
F: FnMut(T) -> bool,
{
while if ok > ng { ok - ng } else { ng - ok } > threshold {
let mid = if ok > ng {
ng + (ok - ng) / T::from_usize(2).unwrap()
} else {
ok + (ng - ok) / T::from_usize(2).unwrap()
};
if check(mid) {
ok = mid;
} else {
ng = mid;
}
}
ok
}

pub fn binary_search_trial<T, F>(mut ok: T, mut ng: T, mut check: F, trial: usize) -> T
where
T: Num + PartialOrd + FromPrimitive + Copy,
F: FnMut(T) -> bool,
{
for _ in 0..trial {
let mid = if ok > ng {
ng + (ok - ng) / T::from_usize(2).unwrap()
} else {
ok + (ng - ok) / T::from_usize(2).unwrap()
};
if check(mid) {
ok = mid;
} else {
ng = mid;
}
}
ok
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod graph;
pub mod algorithm;

0 comments on commit a2be93a

Please sign in to comment.