From 2f5bd88f36639c29ebcc92c916fd0cfcca9f1cb6 Mon Sep 17 00:00:00 2001 From: Nenad Date: Sun, 10 Nov 2024 13:22:45 +0100 Subject: [PATCH] Binary search tree (#299) * Init solution * remove root * Implement * explain problems with trees in immutable languages like Cairo * lint code * Reimplement using Option + Box --- config.json | 8 ++ .../.docs/instructions.append.md | 53 +++++++++++++ .../binary-search-tree/.docs/instructions.md | 47 ++++++++++++ .../binary-search-tree/.meta/config.json | 21 ++++++ .../binary-search-tree/.meta/example.cairo | 74 ++++++++++++++++++ .../binary-search-tree/.meta/tests.toml | 40 ++++++++++ .../practice/binary-search-tree/Scarb.toml | 7 ++ .../practice/binary-search-tree/src/lib.cairo | 31 ++++++++ .../tests/binary_search_tree.cairo | 75 +++++++++++++++++++ 9 files changed, 356 insertions(+) create mode 100644 exercises/practice/binary-search-tree/.docs/instructions.append.md create mode 100644 exercises/practice/binary-search-tree/.docs/instructions.md create mode 100644 exercises/practice/binary-search-tree/.meta/config.json create mode 100644 exercises/practice/binary-search-tree/.meta/example.cairo create mode 100644 exercises/practice/binary-search-tree/.meta/tests.toml create mode 100644 exercises/practice/binary-search-tree/Scarb.toml create mode 100644 exercises/practice/binary-search-tree/src/lib.cairo create mode 100644 exercises/practice/binary-search-tree/tests/binary_search_tree.cairo diff --git a/config.json b/config.json index 6678f7a4..4b8abd43 100644 --- a/config.json +++ b/config.json @@ -820,6 +820,14 @@ "prerequisites": [], "difficulty": 4 }, + { + "slug": "binary-search-tree", + "name": "Binary Search Tree", + "uuid": "97941277-12ff-474b-8a41-e89c065e0620", + "practices": [], + "prerequisites": [], + "difficulty": 6 + }, { "slug": "knapsack", "name": "Knapsack", diff --git a/exercises/practice/binary-search-tree/.docs/instructions.append.md b/exercises/practice/binary-search-tree/.docs/instructions.append.md new file mode 100644 index 00000000..ae4f258b --- /dev/null +++ b/exercises/practice/binary-search-tree/.docs/instructions.append.md @@ -0,0 +1,53 @@ +# Instructions append + +Implementing an efficient and modifiable tree structure in Cairo (or any purely functional language with immutable memory) is challenging because these languages are designed to avoid changing data after it’s created. +This immutability means that instead of updating a tree node directly, a new version of the tree must be created whenever you modify it. + +To show why this is the case, imagine a simple binary tree structure where each node has a left and a right child. +Let's say we start with a small tree like this: + +```c + 1 + / \ + 2 3 +``` + +Now, suppose we want to add a new node `4` as the left child of node `2`. +In a purely functional language (like in Cairo or Haskell), memory is immutable, so we can’t simply add node `4` directly to `2`. +Instead, we have to create a new version of each node along the path from the root to the modified node, because every node along this path now points to a new or modified subtree. + +Here’s what the process would look like: + +1. **Add Node 4 to Node 2**: + - Create a new version of node `2`, which now has `4` as its left child. + + ```c + 2' + / + 4 + ``` + +2. **Update the Root Node**: + - Since node `1` originally pointed to the old `2`, we create a new version of the root node `1'` that now points to the updated node `2'` on the left and keeps node `3` on the right. + + ```c + 1' + / \ + 2' 3 + ``` + +So, the resulting tree becomes: + +```c + 1' + / \ + 2' 3 + / + 4 +``` + +This new tree (`1'`) still resembles the original, but with an updated path. +The key point is that we had to re-create each node along the path (`1` to `2`) to preserve immutability, since existing nodes cannot be modified in place. +The original tree still exists (for example, for all references to its original root `1`), while this new tree represents the modified state. + +In large trees, this approach can become expensive, as every new modification requires recreating a path of nodes from the root to the updated node, even if only a small part of the tree is actually changed. diff --git a/exercises/practice/binary-search-tree/.docs/instructions.md b/exercises/practice/binary-search-tree/.docs/instructions.md new file mode 100644 index 00000000..c9bbba5b --- /dev/null +++ b/exercises/practice/binary-search-tree/.docs/instructions.md @@ -0,0 +1,47 @@ +# Instructions + +Insert and search for numbers in a binary tree. + +When we need to represent sorted data, an array does not make a good data structure. + +Say we have the array `[1, 3, 4, 5]`, and we add 2 to it so it becomes `[1, 3, 4, 5, 2]`. +Now we must sort the entire array again! +We can improve on this by realizing that we only need to make space for the new item `[1, nil, 3, 4, 5]`, and then adding the item in the space we added. +But this still requires us to shift many elements down by one. + +Binary Search Trees, however, can operate on sorted data much more efficiently. + +A binary search tree consists of a series of connected nodes. +Each node contains a piece of data (e.g. the number 3), a variable named `left`, and a variable named `right`. +The `left` and `right` variables point at `nil`, or other nodes. +Since these other nodes in turn have other nodes beneath them, we say that the left and right variables are pointing at subtrees. +All data in the left subtree is less than or equal to the current node's data, and all data in the right subtree is greater than the current node's data. + +For example, if we had a node containing the data 4, and we added the data 2, our tree would look like this: + + 4 + / + 2 + +If we then added 6, it would look like this: + + 4 + / \ + 2 6 + +If we then added 3, it would look like this + + 4 + / \ + 2 6 + \ + 3 + +And if we then added 1, 5, and 7, it would look like this + + 4 + / \ + / \ + 2 6 + / \ / \ + 1 3 5 7 diff --git a/exercises/practice/binary-search-tree/.meta/config.json b/exercises/practice/binary-search-tree/.meta/config.json new file mode 100644 index 00000000..2bfd92ae --- /dev/null +++ b/exercises/practice/binary-search-tree/.meta/config.json @@ -0,0 +1,21 @@ +{ + "authors": [ + "0xNeshi" + ], + "files": { + "solution": [ + "src/lib.cairo" + ], + "test": [ + "tests/binary_search_tree.cairo" + ], + "example": [ + ".meta/example.cairo" + ], + "invalidator": [ + "Scarb.toml" + ] + }, + "blurb": "Insert and search for numbers in a binary tree.", + "source": "Josh Cheek" +} diff --git a/exercises/practice/binary-search-tree/.meta/example.cairo b/exercises/practice/binary-search-tree/.meta/example.cairo new file mode 100644 index 00000000..3c0c7a91 --- /dev/null +++ b/exercises/practice/binary-search-tree/.meta/example.cairo @@ -0,0 +1,74 @@ +type BinarySearchTree = Option>; + +#[derive(Drop, Copy)] +struct Node { + value: u32, + left: BinarySearchTree, + right: BinarySearchTree, +} + +#[generate_trait] +pub impl BinarySearchTreeImpl of BinarySearchTreeTrait { + fn new(tree_data: Span) -> BinarySearchTree { + let mut bts: BinarySearchTree = Default::default(); + for value in tree_data { + bts = bts.add(*value); + }; + bts + } + + fn add(self: BinarySearchTree, value: u32) -> BinarySearchTree { + match self { + Option::None => Option::Some( + BoxTrait::new(Node { value, left: Option::None, right: Option::None }) + ), + Option::Some(node) => { + if value <= node.value { + Option::Some( + BoxTrait::new( + Node { + value: node.value, left: node.left.add(value), right: node.right + } + ) + ) + } else { + Option::Some( + BoxTrait::new( + Node { + value: node.value, left: node.left, right: node.right.add(value) + } + ) + ) + } + } + } + } + + fn value(self: @BinarySearchTree) -> Option { + Option::Some((*self)?.value) + } + + fn left(self: @BinarySearchTree) -> @BinarySearchTree { + @match self { + Option::None => Option::None, + Option::Some(bst) => bst.left + } + } + + fn right(self: @BinarySearchTree) -> @BinarySearchTree { + @match self { + Option::None => Option::None, + Option::Some(bst) => bst.right + } + } + + fn sorted_data(self: @BinarySearchTree) -> Span { + let mut res = array![]; + if let Option::Some(node) = self { + res.append_span(node.left.sorted_data()); + res.append(node.value); + res.append_span(node.right.sorted_data()); + } + res.span() + } +} diff --git a/exercises/practice/binary-search-tree/.meta/tests.toml b/exercises/practice/binary-search-tree/.meta/tests.toml new file mode 100644 index 00000000..c7d32021 --- /dev/null +++ b/exercises/practice/binary-search-tree/.meta/tests.toml @@ -0,0 +1,40 @@ +# This is an auto-generated file. +# +# Regenerating this file via `configlet sync` will: +# - Recreate every `description` key/value pair +# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications +# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion) +# - Preserve any other key/value pair +# +# As user-added comments (using the # character) will be removed when this file +# is regenerated, comments can be added via a `comment` key. + +[e9c93a78-c536-4750-a336-94583d23fafa] +description = "data is retained" + +[7a95c9e8-69f6-476a-b0c4-4170cb3f7c91] +description = "insert data at proper node -> smaller number at left node" + +[22b89499-9805-4703-a159-1a6e434c1585] +description = "insert data at proper node -> same number at left node" + +[2e85fdde-77b1-41ed-b6ac-26ce6b663e34] +description = "insert data at proper node -> greater number at right node" + +[dd898658-40ab-41d0-965e-7f145bf66e0b] +description = "can create complex tree" + +[9e0c06ef-aeca-4202-b8e4-97f1ed057d56] +description = "can sort data -> can sort single number" + +[425e6d07-fceb-4681-a4f4-e46920e380bb] +description = "can sort data -> can sort if second number is smaller than first" + +[bd7532cc-6988-4259-bac8-1d50140079ab] +description = "can sort data -> can sort if second number is same as first" + +[b6d1b3a5-9d79-44fd-9013-c83ca92ddd36] +description = "can sort data -> can sort if second number is greater than first" + +[d00ec9bd-1288-4171-b968-d44d0808c1c8] +description = "can sort data -> can sort complex tree" diff --git a/exercises/practice/binary-search-tree/Scarb.toml b/exercises/practice/binary-search-tree/Scarb.toml new file mode 100644 index 00000000..6b6ce880 --- /dev/null +++ b/exercises/practice/binary-search-tree/Scarb.toml @@ -0,0 +1,7 @@ +[package] +name = "binary_search_tree" +version = "0.1.0" +edition = "2024_07" + +[dev-dependencies] +cairo_test = "2.8.2" diff --git a/exercises/practice/binary-search-tree/src/lib.cairo b/exercises/practice/binary-search-tree/src/lib.cairo new file mode 100644 index 00000000..164d4a41 --- /dev/null +++ b/exercises/practice/binary-search-tree/src/lib.cairo @@ -0,0 +1,31 @@ +type BinarySearchTree = Option>; + +#[derive(Drop, Copy)] +struct Node { + value: u32, + left: BinarySearchTree, + right: BinarySearchTree, +} + +#[generate_trait] +pub impl BinarySearchTreeImpl of BinarySearchTreeTrait { + fn new(tree_data: Span) -> BinarySearchTree { + panic!("implement `BinarySearchTreeTrait::new`") + } + + fn value(self: @BinarySearchTree) -> Option { + panic!("implement `BinarySearchTreeTrait::value`") + } + + fn left(self: @BinarySearchTree) -> @BinarySearchTree { + panic!("implement `BinarySearchTreeTrait::left`") + } + + fn right(self: @BinarySearchTree) -> @BinarySearchTree { + panic!("implement `BinarySearchTreeTrait::right`") + } + + fn sorted_data(self: @BinarySearchTree) -> Span { + panic!("implement `BinarySearchTreeTrait::sorted_data`") + } +} diff --git a/exercises/practice/binary-search-tree/tests/binary_search_tree.cairo b/exercises/practice/binary-search-tree/tests/binary_search_tree.cairo new file mode 100644 index 00000000..2f1723f4 --- /dev/null +++ b/exercises/practice/binary-search-tree/tests/binary_search_tree.cairo @@ -0,0 +1,75 @@ +use binary_search_tree::BinarySearchTreeTrait as BinarySearchTree; + +#[test] +fn data_is_retained() { + let bst = BinarySearchTree::new(array![4].span()); + assert_eq!(Option::Some(4), bst.value()); +} + +#[test] +fn smaller_number_at_left_node() { + let bst = BinarySearchTree::new(array![4, 2].span()); + assert_eq!(Option::Some(4), bst.value()); + assert_eq!(Option::Some(2), bst.left().value()); +} + +#[test] +fn same_number_at_left_node() { + let bst = BinarySearchTree::new(array![4, 4].span()); + assert_eq!(Option::Some(4), bst.value()); + assert_eq!(Option::Some(4), bst.left().value()); +} + +#[test] +fn greater_number_at_right_node() { + let bst = BinarySearchTree::new(array![4, 5].span()); + assert_eq!(Option::Some(4), bst.value()); + assert_eq!(Option::Some(5), bst.right().value()); +} + +#[test] +fn can_create_complex_tree() { + let bst = BinarySearchTree::new(array![4, 2, 6, 1, 3, 5, 7].span()); + assert_eq!(Option::Some(4), bst.value()); + assert_eq!(Option::Some(2), bst.left().value()); + assert_eq!(Option::Some(6), bst.right().value()); + assert_eq!(Option::Some(1), bst.left().left().value()); + assert_eq!(Option::Some(3), bst.left().right().value()); + assert_eq!(Option::Some(5), bst.right().left().value()); + assert_eq!(Option::Some(7), bst.right().right().value()); +} + +#[test] +fn can_sort_single_number() { + let mut bts = BinarySearchTree::new(array![2].span()); + let expected = array![2].span(); + assert_eq!(expected, bts.sorted_data()); +} + +#[test] +fn can_sort_if_second_number_is_smaller_than_first() { + let mut bts = BinarySearchTree::new(array![2, 1].span()); + let expected = array![1, 2].span(); + assert_eq!(expected, bts.sorted_data()); +} + +#[test] +fn can_sort_if_second_number_is_same_as_first() { + let mut bts = BinarySearchTree::new(array![2, 2].span()); + let expected = array![2, 2].span(); + assert_eq!(expected, bts.sorted_data()); +} + +#[test] +fn can_sort_if_second_number_is_greater_than_first() { + let mut bts = BinarySearchTree::new(array![2, 3].span()); + let expected = array![2, 3].span(); + assert_eq!(expected, bts.sorted_data()); +} + +#[test] +fn can_sort_complex_tree() { + let mut bts = BinarySearchTree::new(array![2, 1, 3, 6, 7, 5].span()); + let expected = array![1, 2, 3, 5, 6, 7].span(); + assert_eq!(expected, bts.sorted_data()); +}