From 1f53b76188721f161e769f5628a4e58270329a75 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Mon, 8 Jul 2024 14:34:28 +0530 Subject: [PATCH] first commit --- .github/workflows/docs.yml | 32 +++ .github/workflows/tests.yml | 36 +++ .gitignore | 4 + .ruby-version | 1 + CHANGELOG.md | 5 + CODE_OF_CONDUCT.md | 132 +++++++++ Gemfile | 12 + Gemfile.lock | 24 ++ LICENSE.txt | 21 ++ README.md | 39 +++ Rakefile | 8 + bin/console | 11 + bin/setup | 8 + lib/red-black-tree.rb | 229 ++++++++++++++++ lib/red_black_tree/node.rb | 29 ++ lib/red_black_tree/node/implementation.rb | 125 +++++++++ .../node/left_right_element_referencers.rb | 23 ++ lib/red_black_tree/utils.rb | 17 ++ lib/red_black_tree/version.rb | 5 + red-black-tree.gemspec | 34 +++ test/test_helper.rb | 6 + test/test_node.rb | 21 ++ test/test_red_black_tree.rb | 255 ++++++++++++++++++ 23 files changed, 1077 insertions(+) create mode 100644 .github/workflows/docs.yml create mode 100644 .github/workflows/tests.yml create mode 100644 .gitignore create mode 100644 .ruby-version create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 Rakefile create mode 100755 bin/console create mode 100755 bin/setup create mode 100644 lib/red-black-tree.rb create mode 100644 lib/red_black_tree/node.rb create mode 100644 lib/red_black_tree/node/implementation.rb create mode 100644 lib/red_black_tree/node/left_right_element_referencers.rb create mode 100644 lib/red_black_tree/utils.rb create mode 100644 lib/red_black_tree/version.rb create mode 100644 red-black-tree.gemspec create mode 100644 test/test_helper.rb create mode 100644 test/test_node.rb create mode 100644 test/test_red_black_tree.rb diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..f5b01d3 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,32 @@ +name: YARD Docs + +on: + push: + branches: + - main + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Read Ruby version + id: ruby_version + run: echo "ruby-version=$(cat .ruby-version)" >> $GITHUB_ENV + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ env.ruby-version }} + bundler-cache: true + + - name: Generate YARD docs + run: bundle exec yard doc --no-private + + - name: Deploy to GitHub Pages + uses: peaceiris/actions-gh-pages@v4 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: doc diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..7ffc4b3 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,36 @@ +name: Ruby tests + +on: + push: + branches: + - main + + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + name: Ruby ${{ matrix.ruby }} + strategy: + matrix: + ruby: + - '3.0.0' + - '3.1.0' + - '3.2.0' + - '3.3.0' + - '3.3.1' + - '3.3.2' + - '3.3.3' + - '3.3.4' + + steps: + - uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + + - name: Run Ruby tests + run: bundle exec rake test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..797c617 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/.bundle/ +/.yardoc +/doc/ +/tmp/ diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..a0891f5 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +3.3.4 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..13afaf1 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +## [Unreleased] + +## [0.1.0] - 2024-07-08 + +- Initial release diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..67fe8ce --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,132 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official email address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +[INSERT CONTACT METHOD]. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..e0d71f3 --- /dev/null +++ b/Gemfile @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +# Specify your gem's dependencies in red-black-tree.gemspec +gemspec + +gem "rake", "~> 13.0" + +gem "minitest", "~> 5.16" + +gem "yard", '~> 0.9.36' diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..01f7c61 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,24 @@ +PATH + remote: . + specs: + red-black-tree (0.1.0) + +GEM + remote: https://rubygems.org/ + specs: + minitest (5.24.1) + rake (13.2.1) + yard (0.9.36) + +PLATFORMS + arm64-darwin-24 + ruby + +DEPENDENCIES + minitest (~> 5.16) + rake (~> 13.0) + red-black-tree! + yard (~> 0.9.36) + +BUNDLED WITH + 2.5.15 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..f847c2b --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 Joshua Young + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1b38466 --- /dev/null +++ b/README.md @@ -0,0 +1,39 @@ +# RedBlackTree + +TODO: Delete this and the text below, and describe your gem + +Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/red-black-tree`. To experiment with that code, run `bin/console` for an interactive prompt. + +## Installation + +TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org. + +Install the gem and add to the application's Gemfile by executing: + + $ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG + +If bundler is not being used to manage dependencies, install the gem by executing: + + $ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG + +## Usage + +TODO: Write usage instructions here + +## Development + +After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. + +To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org). + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/red-black-tree. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/red-black-tree/blob/main/CODE_OF_CONDUCT.md). + +## License + +The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). + +## Code of Conduct + +Everyone interacting in the RedBlackTree project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/red-black-tree/blob/main/CODE_OF_CONDUCT.md). diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..474cef6 --- /dev/null +++ b/Rakefile @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +require "bundler/gem_tasks" +require "minitest/test_task" + +Minitest::TestTask.create + +task default: %i[test] diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..c0d2e6b --- /dev/null +++ b/bin/console @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "bundler/setup" +require "red-black-tree" + +# You can add fixtures and/or initialization code here to make experimenting +# with your gem easier. You can also use a different console, if you like. + +require "irb" +IRB.start(__FILE__) diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/lib/red-black-tree.rb b/lib/red-black-tree.rb new file mode 100644 index 0000000..8894689 --- /dev/null +++ b/lib/red-black-tree.rb @@ -0,0 +1,229 @@ +# frozen_string_literal: true + +require_relative "red_black_tree/utils" +require_relative "red_black_tree/node" + +class RedBlackTree + include Utils + + # @private + # @return [RedBlackTree::Node, nil] The root node + attr_reader :root + + # @return [Integer] The number of valid/non-leaf nodes + attr_reader :size + + def initialize + @size = 0 + @left_most_node = nil + end + + # Returns true if there are no valid/non-leaf nodes, and false if there are. + # + # @return [true, false] + def empty? + @size == 0 + end + + # Returns true if there are any valid/non-leaf nodes, and false if there are none. + # + # @return [true, false] + def any? + !empty? + end + + # Removes the left most node i.e. the node with the lowest data value from the tree. + # + # @return [RedBlackTree::Node, nil] The removed node + def shift + node = @left_most_node + delete! node if node + node + end + + # Traverses the tree, comparing existing nodes to the node to be added, + # and inserts the node with the appropriate parent and direction. + # + # @param node [RedBlackTree::Node] The node to be added + # @return [RedBlackTree] self + def << node + parent = @root + direction = nil + + while parent + + direction = node <= parent ? Node::LEFT : Node::RIGHT + break if (child = parent[direction]).leaf? + + parent = child + end + + insert! node, parent, direction + end + alias_method :add!, :<< + + # Inserts the given node using the given direction relative to the given parent. + # + # @private Ideally this is only used internally e.g. in #<< which has context on the ideal location for the node + # @param node [RedBlackTree::Node] The node to be inserted + # @param target_parent [RedBlackTree::Node, nil] The parent under which the node should be inserted + # @param direction ["left", "right", nil] The direction of the node relative to the parent + # @return [RedBlackTree] self + def insert! node, target_parent = nil, direction = nil # :nodoc: + if target_parent.nil? + raise ArgumentError, "Target parent must be provided for tree with root" if @root + else + raise ArgumentError, "Target parent direction must be provided" if direction.nil? + raise ArgumentError, "Target parent already has #{direction} child" if (child = target_parent[direction]) && child.valid? + end + + opp_direction = opposite_direction direction if direction + + node.parent = nil + node.left = node.class.new nil + node.left.parent = node + node.right = node.class.new nil + node.right.parent = node + + if target_parent.nil? + @root = node + @root.black! + else + target_parent[direction] = node + node.parent = target_parent + + node.red! + while node.parent && node.parent.red? do + if node.parent.sibling.red? + node.parent.black! + node.parent.sibling.black! + node.parent.parent.red! + node = node.parent.parent + else + if node.position == direction + node = node.parent + rotate_sub_tree! node, opp_direction + end + + node.parent.black! + node.parent.parent.red! + rotate_sub_tree! node.parent.parent, direction + end + + @root.black! + end + end + + node.validate! @root == node + + @size += 1 + update_left_most_node! + + self + end + + # Removes the given node from the tree. + # + # @param node [RedBlackTree::Node] The node to be removed + # @return [RedBlackTree] self + def delete! node + if node.children_are_valid? + successor = node.right + successor = successor.left until successor.left.leaf? + node.swap_data_with! successor + delete successor + elsif node.single_child_is_valid? + valid_child = node.children.find(&:valid?) + valid_child.black! + node.swap_parent_with! valid_child + elsif node.children_are_leaves? + if @root && @root == node + @root = nil + elsif node.red? + leaf = node.class.new nil + node.swap_parent_with! leaf + else + direction = node.position + opp_direction = opposite_direction direction + + loop do + if node.sibling.red? + node.parent.red! + node.sibling.black! + rotate_sub_tree! node.parent, direction + end + + if node.distant_nephew.valid? && node.distant_nephew.red? + case node.parent.colour + when Node::RED then node.sibling.red! + when Node::BLACK then node.sibling.black! + end + node.parent.black! + node.distant_nephew.black! + rotate_sub_tree! node.parent, direction + + break + end + + if node.close_nephew.valid? && node.close_nephew.red? + node.sibling.red! + node.close_nephew.black! + rotate_sub_tree! node.sibling, opp_direction + end + + if node.parent.red? + node.sibling.red! + node.parent.black! + + break + end + end + + leaf = node.class.new nil + node.swap_parent_with! leaf + end + end + + node.validate_free! + + @size -= 1 + update_left_most_node! + + self + end + + private + + def rotate_sub_tree! node, direction + opp_direction = opposite_direction direction + opp_direction_child = node[opp_direction] + + node[opp_direction] = opp_direction_child[direction] + opp_direction_child[direction].parent = node + + opp_direction_child.parent = node.parent + + if node.parent + node.parent[node.position] = opp_direction_child + else + @root = opp_direction_child + end + + opp_direction_child[direction] = node + node.parent = opp_direction_child + + opp_direction_child # new sub-tree root + end + + def update_left_most_node! + unless @root + @left_most_node = nil + return + end + + current = @root + current = current.left until current.left.leaf? + + @left_most_node = current + end +end diff --git a/lib/red_black_tree/node.rb b/lib/red_black_tree/node.rb new file mode 100644 index 0000000..8d913b9 --- /dev/null +++ b/lib/red_black_tree/node.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +require_relative "node/implementation" + +class RedBlackTree + class Node + include Implementation + + # @return [any] The data/value representing the node + attr_reader :data + + # @param data [any] A non-nil data/value representing the node + # @return [Node] A new instance of Node + def initialize data + @data = data # TODO: Disallow `nil` data + @colour = data.nil? ? BLACK : nil + @parent = @left = @right = nil + + validate_free! + end + + # Needs to be implemented in a subclass of {Node}. + # Will be used to calculate the ideal position of this node when adding it + # to a tree. + def <=> other + raise NotImplementedError, "Comparable operator <=> must be implemented in subclass" + end + end +end diff --git a/lib/red_black_tree/node/implementation.rb b/lib/red_black_tree/node/implementation.rb new file mode 100644 index 0000000..a2e78db --- /dev/null +++ b/lib/red_black_tree/node/implementation.rb @@ -0,0 +1,125 @@ +# frozen_string_literal: true + +require_relative "../utils" +require_relative "left_right_element_referencers" + +class RedBlackTree + class Node + module Implementation # @private + class StructuralError < StandardError; end + + include Utils + include Comparable + + RED = "red" + BLACK = "black" + COLOURS = [RED, BLACK].freeze + + LEFT = "left" + RIGHT = "right" + DIRECTIONS = [LEFT, RIGHT].freeze + + attr_reader :colour + attr_accessor :tree, :parent + attr_accessor :left, :right + include LeftRightElementReferencers + + def red? = @colour == RED + def red! = @colour = RED + + def black? = @colour == BLACK + def black! = @colour = BLACK + + def leaf? = black? && @data.nil? + def valid? = (red? || black?) && !!@data + + def children_are_leaves? = children.all?(&:leaf?) + def children_are_valid? = children.all?(&:valid?) + def single_child_is_leaf? = children.any?(&:leaf?) && !children_are_leaves? + alias_method :single_child_is_valid?, :single_child_is_leaf? + + def position + return unless @parent + + case self + when @parent.left then LEFT + when @parent.right then RIGHT + else raise StructuralError, "Disowned by parent" + end + end + + def opposite_position + return unless @parent + + opposite_direction position + end + + def sibling + return unless @parent + + @parent[opposite_position] + end + + def children + [@left, @right] + end + + def close_nephew + return unless sibling + + sibling[position] + end + + def distant_nephew + return unless sibling + + sibling[opposite_position] + end + + def validate! is_root = false + return if (@parent || is_root) && @left && @right + + raise StructuralError, "Node is invalid" + end + + def validate_free! + anchors = [] + anchors << "parent" if @parent + anchors << "left child" if @left && @left.valid? + anchors << "right child" if @right && @right.valid? + return if anchors.empty? + + raise StructuralError, "Node is still chained to #{anchors.join(", ")}" + end + + def swap_data_with! other_node + temp_data = @data + @data = other_node.data + other_node.data = temp_data + end + + def swap_colour_with! other_node + temp_colour = @colour + + case other_node.colour + when RED then red! + when BLACK then black! + end + + case temp_colour + when RED then other_node.red! + when BLACK then other_node.black! + end + end + + def swap_parent_with! other_node + # this case should be handled by the tree + raise ArgumentError, "Cannot replace parentless node" unless @parent + + @parent[position] = other_node + other_node.parent = @parent + @parent = nil + end + end + end +end diff --git a/lib/red_black_tree/node/left_right_element_referencers.rb b/lib/red_black_tree/node/left_right_element_referencers.rb new file mode 100644 index 0000000..d54947d --- /dev/null +++ b/lib/red_black_tree/node/left_right_element_referencers.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +class RedBlackTree + class Node + module LeftRightElementReferencers # @private + def [] direction + case direction + when Node::LEFT then @left + when Node::RIGHT then @right + else raise ArgumentError, "Direction must be one of #{DIRECTIONS}" + end + end + + def []= direction, node + case direction + when Node::LEFT then @left = node + when Node::RIGHT then @right = node + else raise ArgumentError, "Direction must be one of #{DIRECTIONS}" + end + end + end + end +end diff --git a/lib/red_black_tree/utils.rb b/lib/red_black_tree/utils.rb new file mode 100644 index 0000000..56d3803 --- /dev/null +++ b/lib/red_black_tree/utils.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +class RedBlackTree + module Utils # @private + private + + def opposite_direction direction + case direction + when "up" then "down" + when "right" then "left" + when "down" then "up" + when "left" then "right" + else raise ArgumentError, "Invalid direction" + end + end + end +end diff --git a/lib/red_black_tree/version.rb b/lib/red_black_tree/version.rb new file mode 100644 index 0000000..5adfd27 --- /dev/null +++ b/lib/red_black_tree/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +class RedBlackTree + VERSION = "0.1.0" +end diff --git a/red-black-tree.gemspec b/red-black-tree.gemspec new file mode 100644 index 0000000..501fe1d --- /dev/null +++ b/red-black-tree.gemspec @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require_relative "lib/red_black_tree/version" + +Gem::Specification.new do |spec| + spec.name = "red-black-tree" + spec.version = RedBlackTree::VERSION + spec.authors = ["Joshua Young"] + spec.email = ["djry1999@gmail.com"] + + spec.summary = "Red-Black Tree Data Structure for Ruby" + spec.homepage = "https://github.com/joshuay03/red-black-tree" + spec.license = "MIT" + spec.required_ruby_version = ">= 3.0.0" + + spec.metadata["allowed_push_host"] = "https://rubygems.org" + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["documentation_uri"] = "https://joshuay03.github.io/red-black-tree/" + spec.metadata["source_code_uri"] = spec.homepage + spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md" + + # Specify which files should be added to the gem when it is released. + # The `git ls-files -z` loads the files in the RubyGem that have been added into git. + gemspec = File.basename(__FILE__) + spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, err: IO::NULL) do |ls| + ls.readlines("\x0", chomp: true).reject do |f| + (f == gemspec) || + f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile]) + end + end + spec.bindir = "exe" + spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } + spec.require_paths = ["lib"] +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..e21197f --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +$LOAD_PATH.unshift File.expand_path("../lib", __dir__) +require "red-black-tree" + +require "minitest/autorun" diff --git a/test/test_node.rb b/test/test_node.rb new file mode 100644 index 0000000..838d208 --- /dev/null +++ b/test/test_node.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +require "test_helper" + +class TestNode < Minitest::Test + def test_new_node + node = RedBlackTree::Node.new "root" + assert_nil node.colour + assert_nil node.parent + assert_nil node.left + assert_nil node.right + end + + def test_new_leaf_node + node = RedBlackTree::Node.new nil + assert node.black? + assert_nil node.parent + assert_nil node.left + assert_nil node.right + end +end diff --git a/test/test_red_black_tree.rb b/test/test_red_black_tree.rb new file mode 100644 index 0000000..0c664ae --- /dev/null +++ b/test/test_red_black_tree.rb @@ -0,0 +1,255 @@ +# frozen_string_literal: true + +require "test_helper" + +class TestRedBlackTree < Minitest::Test + def test_that_it_has_a_version_number + refute_nil ::RedBlackTree::VERSION + end + + def test_new_tree_no_root + tree = RedBlackTree.new + assert_nil tree.root + end + + class TestEmpty < Minitest::Test + def test_new_tree + tree = RedBlackTree.new + assert_equal 0, tree.size + assert tree.empty? + end + + def test_single_node_tree + tree = RedBlackTree.new + node = RedBlackTree::StringNode.new "root" + tree.insert! node + assert_equal 1, tree.size + refute tree.empty? + end + end + + class TestAny < Minitest::Test + def test_new_tree + tree = RedBlackTree.new + assert_equal 0, tree.size + refute tree.any? + end + + def test_single_node_tree + tree = RedBlackTree.new + node = RedBlackTree::StringNode.new "root" + tree.insert! node + assert_equal 1, tree.size + assert tree.any? + end + end + + class TestInsert < Minitest::Test + def test_new_tree_insert + tree = RedBlackTree.new + node = RedBlackTree::StringNode.new "root" + tree.insert! node + assert_equal 1, tree.size + assert_equal node, (root_node = tree.root) + assert root_node.black? + assert root_node.left.leaf? + assert root_node.right.leaf? + end + + def test_single_node_tree_insert + tree = RedBlackTree.new + node = RedBlackTree::StringNode.new "root" + tree.insert! node + assert_equal 1, tree.size + assert_equal node, (root_node = tree.root) + assert root_node.black? + + node = RedBlackTree::StringNode.new "left child" + tree.insert! node, root_node, "left" + assert_equal 2, tree.size + assert root_node.black? + assert node.red? + assert_equal node, root_node.left + assert root_node.right.leaf? + end + + def test_single_node_tree_insert_without_parent + tree = RedBlackTree.new + node = RedBlackTree::StringNode.new "root 1" + tree.insert! node + assert_equal 1, tree.size + assert_equal node, tree.root + + node = RedBlackTree::StringNode.new "root 2" + error = assert_raises do + tree.insert! node + end + assert_equal error.message, "Target parent must be provided for tree with root" + end + + def test_single_node_tree_insert_without_direction + tree = RedBlackTree.new + node = RedBlackTree::StringNode.new "root" + tree.insert! node + assert_equal 1, tree.size + assert_equal node, (root_node = tree.root) + + node = RedBlackTree::StringNode.new "child" + error = assert_raises do + tree.insert! node, root_node + end + assert_equal error.message, "Target parent direction must be provided" + end + + def test_tree_with_sub_tree_insert + tree = RedBlackTree.new + node = RedBlackTree::StringNode.new "root" + tree.insert! node + assert_equal 1, tree.size + assert_equal node, (root_node = tree.root) + assert root_node.black? + + node = RedBlackTree::StringNode.new "left child" + tree.insert! node, root_node, "left" + assert_equal 2, tree.size + assert_equal node, (child_node = root_node.left) + assert root_node.black? + assert child_node.red? + + node = RedBlackTree::StringNode.new "left child right child" + tree.insert! node, child_node, "right" + assert_equal 3, tree.size + # new balanced state + assert_equal "left child right child", (new_root_node = tree.root).data + assert new_root_node.black? + assert_equal "left child", (new_left_child = new_root_node.left).data + assert new_left_child.red? + assert new_left_child.children.all?(&:leaf?) + assert_equal "root", (new_right_child = new_root_node.right).data + assert new_right_child.red? + assert new_right_child.children.all?(&:leaf?) + end + + def test_tree_with_sub_tree_insert_with_existing_child + tree = RedBlackTree.new + node = RedBlackTree::StringNode.new "root" + tree.insert! node + assert_equal 1, tree.size + assert_equal node, (root_node = tree.root) + + node = RedBlackTree::StringNode.new "left child 1" + tree.insert! node, root_node, "left" + assert_equal 2, tree.size + assert_equal node, (child_node = root_node.left) + + node = RedBlackTree::StringNode.new "left child 2" + error = assert_raises do + tree.insert! node, root_node, "left" + end + assert_equal error.message, "Target parent already has left child" + end + + # fine for these tests where just the == operator is required + class RedBlackTree::StringNode < RedBlackTree::Node + def <=> other + self.data <=> other.data + end + end + end + + class TestAdd < Minitest::Test + def test_new_tree_add + tree = RedBlackTree.new + node = RedBlackTree::IntegerNode.new 10 + tree << node + assert_equal 1, tree.size + assert_equal node, (root_node = tree.root) + assert root_node.black? + assert root_node.left.leaf? + assert root_node.right.leaf? + end + + def test_single_node_tree_add_lesser_node + tree = RedBlackTree.new + node = RedBlackTree::IntegerNode.new 10 + tree << node + assert_equal 1, tree.size + assert_equal node, (root_node = tree.root) + + node = RedBlackTree::IntegerNode.new 5 + tree << node + assert_equal 2, tree.size + assert_equal node, root_node.left + end + + def test_single_node_tree_add_greater_node + tree = RedBlackTree.new + node = RedBlackTree::IntegerNode.new 10 + tree << node + assert_equal 1, tree.size + assert_equal node, (root_node = tree.root) + + node = RedBlackTree::IntegerNode.new 15 + tree << node + assert_equal 2, tree.size + assert_equal node, root_node.right + end + + def test_single_node_tree_add_equal_node + tree = RedBlackTree.new + node = RedBlackTree::IntegerNode.new 10 + tree << node + assert_equal 1, tree.size + assert_equal node, (root_node = tree.root) + + node = RedBlackTree::IntegerNode.new 15 + tree << node + assert_equal 2, tree.size + assert_equal node, root_node.right + end + end + + class TestDelete < Minitest::Test + def test_delete_non_root_black_node_with_leaf_children + tree = RedBlackTree.new + node = RedBlackTree::IntegerNode.new 10 + tree << node + assert_equal 1, tree.size + assert_equal node, (root_node = tree.root) + + node = RedBlackTree::IntegerNode.new 5 + tree << node + assert_equal 2, tree.size + assert_equal node, (target_node_sibling = root_node.left) + + node = RedBlackTree::IntegerNode.new 15 + tree << node + assert_equal 3, tree.size + assert_equal node, (target_node = root_node.right) + assert target_node.red? + assert target_node.children_are_leaves? + + node = RedBlackTree::IntegerNode.new 1 + tree << node + assert_equal 4, tree.size + assert_equal node, target_node_sibling.left + # new target node state + assert_equal target_node, root_node.right + assert target_node.black? + assert target_node.children_are_leaves? + + tree.delete! target_node + assert_equal 3, tree.size + # new balanced state + assert_equal 5, (new_root_node = tree.root).data + assert_equal 1, new_root_node.left.data + assert_equal 10, new_root_node.right.data + end + end + + class RedBlackTree::IntegerNode < RedBlackTree::Node + def <=> other + self.data <=> other.data + end + end +end