Use of children count and simple error handling
This commit is contained in:
parent
c3b04be872
commit
5c99e80670
2 changed files with 30 additions and 4 deletions
|
|
@ -12,10 +12,15 @@ pub struct Node {
|
|||
}
|
||||
|
||||
impl Node {
|
||||
pub fn new(children: Option<Vec<Node>>, handler: NodeHandler) -> Self {
|
||||
pub fn new(
|
||||
children: Option<Vec<Node>>,
|
||||
handler: NodeHandler,
|
||||
max_children_count: Option<usize>,
|
||||
) -> Self {
|
||||
Self {
|
||||
children: children.unwrap_or(vec![]),
|
||||
handler: handler,
|
||||
max_children_count,
|
||||
}
|
||||
}
|
||||
pub fn get_value(&self) -> f64 {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,14 @@
|
|||
use crate::node::Node;
|
||||
use crate::node::NodeHandler;
|
||||
use crate::node::functions;
|
||||
use crate::node::handler::NodeHandler;
|
||||
use rand::random_range;
|
||||
|
||||
const PICK_STOP_PROBABILITY: u8 = 2;
|
||||
|
||||
pub enum NodeManipulationError {
|
||||
TooMuchChildren(Node),
|
||||
}
|
||||
|
||||
pub struct NodeModifier<'a> {
|
||||
picked_node: &'a mut Node,
|
||||
function_mutation_pool: Vec<fn(Vec<f64>) -> f64>,
|
||||
|
|
@ -57,16 +61,33 @@ impl<'a> NodeModifier<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn add_node(&mut self, node: Node) {
|
||||
pub fn add_node(&mut self, node: Node) -> Result<(), NodeManipulationError> {
|
||||
if let Some(x) = self.picked_node.max_children_count {
|
||||
if self.picked_node.children.len() + 1 >= x {
|
||||
return Err(NodeManipulationError::TooMuchChildren(node));
|
||||
}
|
||||
}
|
||||
self.picked_node.children.push(node);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn insert_node(&mut self, mut node: Node, between: Option<usize>) {
|
||||
pub fn insert_node(
|
||||
&mut self,
|
||||
mut node: Node,
|
||||
between: Option<usize>,
|
||||
) -> Result<(), NodeManipulationError> {
|
||||
if let Some(x) = self.picked_node.max_children_count {
|
||||
if self.picked_node.children.len() + 1 >= x {
|
||||
return Err(NodeManipulationError::TooMuchChildren(node));
|
||||
}
|
||||
}
|
||||
let children_count = self.picked_node.children.len();
|
||||
let operated_index = between.unwrap_or(random_range(0..children_count));
|
||||
let moved = self.picked_node.children.remove(operated_index);
|
||||
node.children.push(moved);
|
||||
self.picked_node.children.insert(operated_index, node);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn mutate_node(&mut self) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue