Difference between two Iterator<Range<usize>>'s - algorithm

My program represents sets as Iterator<Range<usize>>, and I'm trying to implement set subtraction.
Essentially, I'm trying to create a function set_diff such that:
let a = vec![1..5, 7..10];
let a = a.into_iter();
let b = vec![3..9];
let b = b.into_iter();
let mut c = set_diff(a, b);
assert_eq!(c.next(), Some(1..3));
assert_eq!(c.next(), Some(9..10));
assert_eq!(c.next(), None);
This is complicated by the fact that this code should run with #[no_std]. The real iterators a and b are able to be cloned, if that helps.
I've made a probably-working iterator for the difference of two ranges, below. The only possible solution I've thought of would be to flatmap this over each element of A for every element in B, but that's really inefficient.
use std::cmp::{max, min};
use std::ops::Range;
/// An extension for Ranges allowing subtraction.
pub trait RangeExt<T: Ord> {
fn difference(self, other: Self) -> DiffIter<T>;
}
impl RangeExt<usize> for Range<usize> {
fn difference(self, other: Range<usize>) -> DiffIter<usize> {
DiffIter {
state: Some(match (self.start < other.start, self.end < other.end) {
(false, false) => DiffIterState::One(Range {
start: max(other.end, self.start),
end: self.end,
}),
(false, true) => DiffIterState::None,
(true, false) => DiffIterState::Two(Range {
start: self.start,
end: other.start,
}, Range {
start: other.end,
end: self.end,
}),
(true, true) => DiffIterState::One(Range {
start: self.start,
end: if other.start == self.end {
self.end
} else {
min(other.start - 1, self.end)
}
}),
})
}
}
}
/// A iterator for the difference of two ranges.
pub struct DiffIter<T> {
state: Option<DiffIterState<T>>,
}
impl<T> Iterator for DiffIter<T> {
type Item = Range<T>;
fn next(&mut self) -> Option<Range<T>> {
let (out, next) = match self.state.take().unwrap() {
DiffIterState::None => {
(None, DiffIterState::None)
},
DiffIterState::One(r) => {
(Some(r), DiffIterState::None)
},
DiffIterState::Two(l, r) => {
(Some(l), DiffIterState::One(r))
},
};
self.state = Some(next);
out
}
}
enum DiffIterState<T> {
None,
One(Range<T>),
Two(Range<T>, Range<T>),
}

Related

egui combobox vector for selected

I am trying to use a vector instead of the enum specified in the docs but I have no clue how to implement the selected part. My current code is
egui::ComboBox::from_label("Take your pick")
.selected_text(format!("{}", self.radio[0]))
.show_ui(ui, |ui| {
for i in 0..self.radio.len() {
ui.selectable_value(&mut &self.radio, &self.radio, &self.radio[i]);
}
});
can anyone give me an idea. I do not mind using enum but I do not know how many things will be in it.
I stumbled on the same problem, and I have found a solution. The solution is to add a new Variable to the self. Here is a basic example on the Enum select and the Vector select. Hope this helps out anyone who has run into the same problem.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use eframe::egui;
fn main() {
let options = eframe::NativeOptions::default();
eframe::run_native(
"Test Select with Enum and Vector",
options,
Box::new(|_cc| Box::new(MyApp::default())),
);
}
#[derive(PartialEq)]
#[derive(Debug)]
enum OS_Select {
First,
Second,
Third,
}
struct MyApp {
selected: usize,
radio: OS_Select,
selector_vec: Vec<String>,
}
impl Default for MyApp {
fn default() -> Self {
Self {
selected: 0,
radio: OS_Select::First,
selector_vec: get_vec(),
}
}
}
fn get_vec() -> Vec<String> {
let vecs = [
"1".to_string(),
"2".to_string(),
"3".to_string(),
].to_vec();
return vecs;
}
impl eframe::App for MyApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("Select with enum");
ui.horizontal(|ui| {
ui.radio_value(&mut self.radio, OS_Select::First, "First");
ui.radio_value(&mut self.radio, OS_Select::Second, "Second");
ui.radio_value(&mut self.radio, OS_Select::Third, "Third");
});
ui.end_row();
ui.heading("Select with Vectors");
egui::ComboBox::from_label("Take your pick")
.selected_text(format!("{}", &self.selector_vec[self.selected]))
.show_ui(ui, |ui| {
for i in 0..self.selector_vec.len() {
let value = ui.selectable_value(&mut &self.selector_vec[i], &self.selector_vec[self.selected], &self.selector_vec[i]);
if (value.clicked()) {
self.selected = i;
}
}
});
ui.end_row();
});
}
fn save(&mut self, _storage: &mut dyn eframe::Storage) {}
fn on_close_event(&mut self) -> bool {
true
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {}
fn auto_save_interval(&self) -> std::time::Duration {
std::time::Duration::from_secs(30)
}
fn max_size_points(&self) -> egui::Vec2 {
egui::Vec2::INFINITY
}
fn clear_color(&self, _visuals: &egui::Visuals) -> egui::Rgba {
// NOTE: a bright gray makes the shadows of the windows look weird.
// We use a bit of transparency so that if the user switches on the
// `transparent()` option they get immediate results.
egui::Color32::from_rgba_unmultiplied(12, 12, 12, 180).into()
// _visuals.window_fill() would also be a natural choice
}
fn persist_native_window(&self) -> bool {
true
}
fn persist_egui_memory(&self) -> bool {
true
}
fn warm_up_enabled(&self) -> bool {
false
}
fn post_rendering(&mut self, _window_size_px: [u32; 2], _frame: &eframe::Frame) {}
}

Trie: cannot borrow `_` as mutable more than once at a time

I want to implement some basic methods for Trie.
use std::collections::HashMap;
#[derive(Debug)]
struct TrieNode {
chs: HashMap<char, TrieNode>,
value: Option<i32>,
}
#[derive(Debug)]
struct Trie {
root: TrieNode,
}
impl Trie {
fn new() -> Trie {
Trie {
root: TrieNode {
chs: HashMap::new(),
value: None,
},
}
}
fn add_string(&mut self, string: String, value: i32) {
let mut current_node = &mut self.root;
for c in string.chars() {
current_node = current_node.chs.entry(c).or_insert(TrieNode {
chs: HashMap::new(),
value: None,
});
}
current_node.value = Some(value);
}
fn delete(&mut self, key: &String) -> Option<i32> {
if key.is_empty() {
// if key is empty, no need to delete
return None;
}
let mut current_node = &mut self.root;
for (ind, ch) in key.chars().enumerate() {
match current_node.chs.get_mut(&ch) {
Some(node) => {
if ind < key.len() - 1 {
current_node = node;
}
}
None => return None,
}
}
// here current_node is actually the previous node of the deleted node
let temp = current_node.chs.remove(&key.chars().last().unwrap());
match temp {
Some(node) => node.value,
None => None,
}
}
}
The method delete is to remove a key (from a Trie) and returns the value corresponding to that key. However, I got the following error.
error[E0499]: cannot borrow `current_node.chs` as mutable more than once at a time
--> src/main.rs:118:19
|
118 | match current_node.chs.get_mut(&ch) {
| ^^^^^^^^^^^^^^^^ mutable borrow starts here in previous iteration of loop
I'm not exactly sure where the borrow checker is getting tripped up, but you can fix it by hoisting the if check:
let mut current_node = &mut self.root;
for (ind, ch) in key.chars().enumerate() {
if ind < key.len() - 1 {
match current_node.chs.get_mut(&ch) {
Some(node) => {
current_node = node;
}
None => return None,
}
}
}
It skips over even checking if the leaf node exists, but your remove( match already covers that case.
Also, your ind < key.len() - 1 check assumes that the last character is ascii. It may be true for your use case, but if not you can use this answer to iterate until the penultimate character instead.
As the error message explains, you cannot borrow a value (current_node.chs) as mutable more than once at a time.
One solution is to derive the Clone trait for TrieNode. Clone is a common trait for the ability to explicitly duplicate an object:
#[derive(Debug, Clone)]
struct TrieNode {
chs: HashMap<char, TrieNode>,
value: Option<i32>,
}
Now instead of borrowing self.root, you can clone it:
fn delete(&mut self, key: &String) -> Option<i32> {
if key.is_empty() {
return None
}
// clone `self.root`
let mut current_node = self.root.clone();
for (ind, ch) in key.chars().enumerate() {
match current_node.chs.get_mut(&ch) {
Some(node) => {
if ind < key.len() - 1 {
// clone `node`
current_node = node.clone();
}
// ...
If performance is an issue, then cloning is probably not the best idea. However, it is still an option and may or may not suit your use case.

Is there a way to directly access a field value in an enum struct without pattern matching?

I wish that enums in Rust can be used like Haskell's productive type. I want to
access a field's value directly
assign a field's value directly or make a clone with the changing value.
Directly means that not using too long pattern matching code, but just could access like let a_size = a.size.
In Haskell:
data TypeAB = A {size::Int, name::String} | B {size::Int, switch::Bool} deriving Show
main = do
let a = A 1 "abc"
let b = B 1 True
print (size a) -- could access a field's value directly
print (name a) -- could access a field's value directly
print (switch b) -- could access a field's value directly
let aa = a{size=2} -- could make a clone directly with the changing value
print aa
I tried two styles of Rust enum definition like
Style A:
#[derive(Debug)]
enum EntryType {
A(TypeA),
B(TypeB),
}
#[derive(Debug)]
struct TypeA {
size: u32,
name: String,
}
#[derive(Debug)]
struct TypeB {
size: u32,
switch: bool,
}
fn main() {
let mut ta = TypeA {
size: 3,
name: "TAB".to_string(),
};
println!("{:?}", &ta);
ta.size = 2;
ta.name = "TCD".to_string();
println!("{:?}", &ta);
let mut ea = EntryType::A(TypeA {
size: 1,
name: "abc".to_string(),
});
let mut eb = EntryType::B(TypeB {
size: 1,
switch: true,
});
let vec_ab = vec![&ea, &eb];
println!("{:?}", &ea);
println!("{:?}", &eb);
println!("{:?}", &vec_ab);
// Want to do like `ta.size = 2` for ea
// Want to do like `ta.name = "bcd".to_string()` for ea
// Want to do like `tb.switch = false` for eb
// ????
println!("{:?}", &ea);
println!("{:?}", &eb);
println!("{:?}", &vec_ab);
}
Style B:
#[derive(Debug)]
enum TypeCD {
TypeC { size: u32, name: String },
TypeD { size: u32, switch: bool },
}
fn main() {
// NOTE: Rust requires representative struct name before each constructor
// TODO: Check constructor name can be duplicated
let mut c = TypeCD::TypeC {
size: 1,
name: "abc".to_string(),
};
let mut d = TypeCD::TypeD {
size: 1,
switch: true,
};
let vec_cd = vec![&c, &d];
println!("{:?}", &c);
println!("{:?}", &d);
println!("{:?}", &vec_cd);
// Can't access a field's value like
// let c_size = c.size
let c_size = c.size; // [ERROR]: No field `size` on `TypeCD`
let c_name = c.name; // [ERROR]: No field `name` on `TypeCD`
let d_switch = d.switch; // [ERROR]: No field `switch` on `TypeCD`
// Can't change a field's value like
// c.size = 2;
// c.name = "cde".to_string();
// d.switch = false;
println!("{:?}", &c);
println!("{:?}", &d);
println!("{:?}", &vec_cd);
}
I couldn't access/assign values directly in any style. Do I have to implement functions or a trait just to access a field's value? Is there some way of deriving things to help this situation?
What about style C:
#[derive(Debug)]
enum Color {
Green { name: String },
Blue { switch: bool },
}
#[derive(Debug)]
struct Something {
size: u32,
color: Color,
}
fn main() {
let c = Something {
size: 1,
color: Color::Green {
name: "green".to_string(),
},
};
let d = Something {
size: 2,
color: Color::Blue { switch: true },
};
let vec_cd = vec![&c, &d];
println!("{:?}", &c);
println!("{:?}", &d);
println!("{:?}", &vec_cd);
let _ = c.size;
}
If all variant have something in common, why separate them?
Of course, I need to access not common field too.
This would imply that Rust should define what to do when the actual type at runtime doesn't contain the field you required. So, I don't think Rust would add this one day.
You could do it yourself. It will require some lines of code, but that matches the behavior of your Haskell code. However, I don't think this is the best thing to do. Haskell is Haskell, I think you should code in Rust and not try to code Haskell by using Rust. That a general rule, some feature of Rust come directly from Haskell, but what you want here is very odd in my opinion for Rust code.
#[derive(Debug)]
enum Something {
A { size: u32, name: String },
B { size: u32, switch: bool },
}
impl Something {
fn size(&self) -> u32 {
match self {
Something::A { size, .. } => *size,
Something::B { size, .. } => *size,
}
}
fn name(&self) -> &String {
match self {
Something::A { name, .. } => name,
Something::B { .. } => panic!("Something::B doesn't have name field"),
}
}
fn switch(&self) -> bool {
match self {
Something::A { .. } => panic!("Something::A doesn't have switch field"),
Something::B { switch, .. } => *switch,
}
}
fn new_size(&self, size: u32) -> Something {
match self {
Something::A { name, .. } => Something::A {
size,
name: name.clone(),
},
Something::B { switch, .. } => Something::B {
size,
switch: *switch,
},
}
}
// etc...
}
fn main() {
let a = Something::A {
size: 1,
name: "Rust is not haskell".to_string(),
};
println!("{:?}", a.size());
println!("{:?}", a.name());
let b = Something::B {
size: 1,
switch: true,
};
println!("{:?}", b.switch());
let aa = a.new_size(2);
println!("{:?}", aa);
}
I think there is currently no built-in way of accessing size directly on the enum type. Until then, enum_dispatch or a macro-based solution may help you.

Delete a node in singly linked list in Rust

I am new to Rust and want to write linked list in Rust to have fun. I am confused about how to delete a node in the linked list. Here is my simple code.
#[derive(Debug)]
struct Node{
v: usize,
next: Option<Box<Node>>,
}
struct LinkedList {
head: Option<Box<Node>>,
}
impl LinkedList {
fn remove(&mut self, v: usize) -> Option<usize> {
let mut current_node: &mut Option<Box<Node>> = &mut self.head;
loop {
match current_node {
None => break,
Some(node) => {
if node.v == v {
// current_node = what?
// ???????????????
break;
} else {
current_node = &mut node.next;
}
},
};
}
match current_node.take().map(|x| *x) {
Some(node) => {
*current_node = node.next;
return Some(node.v)
},
None => None,
}
}
}
And here is the rust playground. I am using the nightly version and edition = 2018. In the loop, I try to find the node whose next node contains the value that I search for. However, I am confused about what to write in the ?? position.
There isn't really code that can go in that space to fix it; you'll need to make some bigger changes.
One of the problems is that you have mutably borrowed the current node in current_node, but then need to mutate it while that reference still exists.
Making use of non-lexical lifetimes in Edition 2018, you can do:
impl LinkedList {
fn remove(&mut self, v: usize) -> Option<usize> {
let mut current = &mut self.head;
loop {
match current {
None => return None,
Some(node) if node.v == v => {
*current = node.next.take();
return Some(v);
},
Some(node) => {
current = &mut node.next;
}
}
}
}
}
Somehow, using the match guard if node.v == v to make two match arms, instead of using an if condition inside one match arm, lets the borrower checker deduce that this is safe. I'm not sure why the if statement inside the match arm isn't allowed - there are some of the opinion that this could be a bug.
inspire by above answer, my solution is:
fn removeKFromList(mut head: ListNode<i32>, k: i32) -> ListNode<i32> {
if head.is_none() {
return None;
}
let mut current = &mut head;
loop {
match current {
None => break,
Some(node) if node.value == k => {
*current = node.next.take();
},
Some(node) => {
current = &mut node.next;
}
}
}
return head;
}
Here is solution, if you have generic List, which accepts arbitrary type of content type T and returns deleted content to caller:
impl<T> LinkedList<T> {
pub fn remove_f<F: Fn(&T) -> bool>(&mut self, comparator: F) -> Option<T> {
let mut curr_link = &mut self.head;
loop {
match curr_link {
None => return None,
Some(node_ref) if comparator(&node_ref.elem) => {
let node = curr_link.take().unwrap();
*curr_link = node.next;
return Some(node.elem);
},
Some(node) => curr_link = &mut node.next,
};
}
}
}
Use example, assume T = &str and list contains element with value "1" and no element with value "smth":
assert_eq!(list.remove_f(|node| "1".eq(node.deref())), Some("1"));
assert_eq!(list.remove_f(|node| "smth".eq(node.deref())), None);

How do I sort `NaN` so that it is greater than any other number, and equal to any other `NaN`?

I'm sorting a vector based on two criteria. The first is a floating point that can be NaN, the second is a string which is used to break ties lexicographically.
vec.sort_by(|a, b| {
match (foo(a) as f64 / bar(a) as f64).partial_cmp(&(foo(b) as f64 / bar(b) as f64)) {
Some(x) => {
Ordering::Equal => name(a).cmp(name(b)),
other => other,
}
None() => {
//Not sure what to put here.
}
}
}
foo(a) returns int > 0,
bar(a) returns int >= 0,
name(a) returns & String.
How do I sort NaN so that it is greater than any other number, and equal to any other NaN (lexicographic tie-breaker)?
You already know how to handle ties, all you need is to compare floating point in the desired way. Just... write the code that you described:
use std::cmp::Ordering;
use std::f32;
fn main() {
let mut vec = [91.0, f32::NAN, 42.0];
vec.sort_by(|&a, &b| {
match (a.is_nan(), b.is_nan()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => a.partial_cmp(&b).unwrap(),
}
});
println!("{:?}", vec);
}
You could be fancy and wrap that up in a structure that represents the key as well:
use std::cmp::Ordering;
use std::f32;
fn main() {
let mut vec = [91.0, f32::NAN, 42.0];
vec.sort_by_key(|&a| MyNanKey(a));
println!("{:?}", vec);
}
#[derive(Debug, Copy, Clone, PartialEq)]
struct MyNanKey(f32);
impl Eq for MyNanKey {}
impl PartialOrd for MyNanKey {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for MyNanKey {
fn cmp(&self, other: &Self) -> Ordering {
match (self.0.is_nan(), other.0.is_nan()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => self.0.partial_cmp(&other.0).unwrap(),
}
}
}
I did no thinking about if this would be applicable for the various infinities or denormalized floating point values, so beware.

Resources