Last active
November 29, 2022 07:18
-
-
Save jakobrs/d611d3773df6e2901f91bac100a75511 to your computer and use it in GitHub Desktop.
Interval partitioning problem in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
struct Interval { | |
start: i64, | |
end: i64, | |
} | |
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)] | |
struct Endpoint { | |
time: i64, | |
end: End, | |
index: usize, | |
} | |
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)] | |
enum End { | |
Right, | |
Left, | |
} | |
fn partition(intervals: &[Interval]) -> Vec<usize> { | |
let mut endpoints: Vec<_> = intervals | |
.iter() | |
.enumerate() | |
.flat_map(|(index, &Interval { start, end })| { | |
[ | |
Endpoint { | |
time: start, | |
end: End::Left, | |
index, | |
}, | |
Endpoint { | |
time: end, | |
end: End::Right, | |
index, | |
}, | |
] | |
}) | |
.collect(); | |
endpoints.sort(); | |
let depth: usize = endpoints | |
.iter() | |
.scan(0, |st, i| { | |
match i.end { | |
End::Left => *st += 1, | |
End::Right => *st -= 1, | |
} | |
Some(*st) | |
}) | |
.max() | |
.unwrap(); | |
let mut labels = vec![0; intervals.len()]; | |
let mut available_labels: Vec<_> = (0..depth).collect(); | |
for endpoint in endpoints { | |
match endpoint.end { | |
End::Left => labels[endpoint.index] = available_labels.pop().unwrap(), | |
End::Right => available_labels.push(labels[endpoint.index]), | |
} | |
} | |
labels | |
} | |
fn main() { | |
let intervals = [ | |
Interval { start: 2, end: 5 }, | |
Interval { start: 0, end: 2 }, | |
Interval { start: 2, end: 4 }, | |
]; | |
let partitions = partition(&intervals); | |
println!("{partitions:?}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment