Implementing Binary Tree in Ruby - ruby

I've been trying to implement BinaryTree class in Ruby, but I'm getting the stack level too deep error, although I don't seem to be using any recursion in that particular piece of code:
1. class BinaryTree
2. include Enumerable
3.
4. attr_accessor :value
5.
6. def initialize( value = nil )
7. #value = value
8. #left = BinaryTree.new # stack level too deep here
9. #right = BinaryTree.new # and here
10. end
11.
12. def empty?
13. ( self.value == nil ) ? true : false
14. end
15.
16. def <<( value )
17. return self.value = value if self.empty?
18.
19. test = self.value <=> value
20. case test
21. when -1, 0
22. self.right << value
23. when 1
24. self.left << value
25. end
26. end # <<
27.
28. end
Edit: My question has gone a little bit off track. The current code setting gives me the stack level too deep error at line 8. However, if I employ Ed S.'s solution
#left = #right = nil
then the << method complains saying: undefined method '<<' for nil:NilClass (NoMethodError) at line 22.
Could anyone suggest how to resolve this? My idea is that if I could somehow tell the BinaryTree class that variables left and right are of instances of BinaryTree (i.e. their type is BinaryTree) it would all be well. Am I wrong?

although I don't seem to be using any recursion in that particular piece of code:
Yet...
def initialize( value = nil )
#value = value
#left = BinaryTree.new # this calls initialize again
#right = BinaryTree.new # and so does this, but you never get there
end
That is infinite recursion. You call initilize, which in turn calls new, which in turn calls initialize... and around we go.
You need to add a guard in there to detect that you have already initialized the main node and are now initializing leafs, in which case, #left and #right should just be set to nil.
def initialize( value=nil, is_sub_node=false )
#value = value
#left = is_sub_node ? nil : BinaryTree.new(nil, true)
#right = is_sub_node ? nil : BinaryTree.new(nil, true)
end
To be honest though... why aren't you just initializing left and right to nil to begin with? They don't have values yet, so what are you gaining? It makes more sense semantically; you create a new list with one element, i.e., elements left and right don't yet exist. I would just use:
def initialize(value=nil)
#value = value
#left = #right = nil
end

1. class BinaryTree
2. include Enumerable
3.
4. attr_accessor :value
5.
6. def initialize( value = nil )
7. #value = value
8. end
9.
10. def each # visit
11. return if self.nil?
12.
13. yield self.value
14. self.left.each( &block ) if self.left
15. self.right.each( &block ) if self.right
16. end
17.
18. def empty?
19. # code here
20. end
21.
22. def <<( value ) # insert
23. return self.value = value if self.value == nil
24.
25. test = self.value <=> value
26. case test
27. when -1, 0
28. #right = BinaryTree.new if self.value == nil
29. self.right << value
30. when 1
31. #left = BinaryTree.new if self.value == nil
32. self.left << value
33. end
34. end # <<
35. end

You might need to fix the infinite recursion in your code. Here's a working example of a binary tree. You need to have a base condition to terminate your recursion somewhere, else it'll be a stack of infinite depth.
Example of Self-Referential Data Structures - A Binary Tree
class TreeNode
attr_accessor :value, :left, :right
# The Tree node contains a value, and a pointer to two children - left and right
# Values lesser than this node will be inserted on its left
# Values greater than it will be inserted on its right
def initialize val, left, right
#value = val
#left = left
#right = right
end
end
class BinarySearchTree
# Initialize the Root Node
def initialize val
puts "Initializing with: " + val.to_s
#root = TreeNode.new(val, nil, nil)
end
# Pre-Order Traversal
def preOrderTraversal(node = #root)
return if (node == nil)
preOrderTraversal(node.left)
preOrderTraversal(node.right)
puts node.value.to_s
end
# Post-Order Traversal
def postOrderTraversal(node = #root)
return if (node == nil)
puts node.value.to_s
postOrderTraversal(node.left)
postOrderTraversal(node.right)
end
# In-Order Traversal : Displays the final output in sorted order
# Display smaller children first (by going left)
# Then display the value in the current node
# Then display the larger children on the right
def inOrderTraversal(node = #root)
return if (node == nil)
inOrderTraversal(node.left)
puts node.value.to_s
inOrderTraversal(node.right)
end
# Inserting a value
# When value > current node, go towards the right
# when value < current node, go towards the left
# when you hit a nil node, it means, the new node should be created there
# Duplicate values are not inserted in the tree
def insert(value)
puts "Inserting :" + value.to_s
current_node = #root
while nil != current_node
if (value < current_node.value) && (current_node.left == nil)
current_node.left = TreeNode.new(value, nil, nil)
elsif (value > current_node.value) && (current_node.right == nil)
current_node.right = TreeNode.new(value, nil, nil)
elsif (value < current_node.value)
current_node = current_node.left
elsif (value > current_node.value)
current_node = current_node.right
else
return
end
end
end
end
bst = BinarySearchTree.new(10)
bst.insert(11)
bst.insert(9)
bst.insert(5)
bst.insert(7)
bst.insert(18)
bst.insert(17)
# Demonstrating Different Kinds of Traversals
puts "In-Order Traversal:"
bst.inOrderTraversal
puts "Pre-Order Traversal:"
bst.preOrderTraversal
puts "Post-Order Traversal:"
bst.postOrderTraversal
=begin
Output :
Initializing with: 10
Inserting :11
Inserting :9
Inserting :5
Inserting :7
Inserting :18
Inserting :17
In-Order Traversal:
5
7
9
10
11
17
18
Pre-Order Traversal:
7
5
9
17
18
11
10
Post-Order Traversal:
10
9
5
7
11
18
17
=end
Ref: http://www.thelearningpoint.net/computer-science/basic-data-structures-in-ruby---binary-search-tre

#pranshantb1984 - The ref you gave is good one but I think there is a small change in code. Need to update PreOrder and PostOrder code as given below
# Post-Order Traversal
def postOrderTraversal(node= #root)
return if (node == nil)
postOrderTraversal(node.left)
postOrderTraversal(node.right)
puts node.value.to_s
end
# Pre-Order Traversal
def preOrderTraversal(node = #root)
return if (node == nil)
puts node.value.to_s
preOrderTraversal(node.left)
preOrderTraversal(node.right)
end
Pre Order Traversal
10 -> 9 -> 5 -> 7 -> 11 -> 18 -> 17
Post Order Traversal
7 -> 5 -> 9 -> 17 -> 18 -> 11 -> 10

Related

How to create a Minimax algorithm comparing arrays

I'm trying to code a "minimax" algorithm for Tic Tac Toe.
Each node of the tree is of the form [nil/Int, String] where the last element is a nine character string describing the board, and the first is an Integer ranking the node, or nil by default.
If the value is nil, it tries to inherit the appropriate value from child nodes.
This is where I get an error, when comparing an array with an array failed.
class Scene_TicTacToe #Script 2/2
def initialize
#Boardstate as a str from top left corner to bottom right corner.
#boardstate = "---------"
#1 = player, -1 = comp
#active_player = 1
end
def wincheck(boardstate=#boardstate)
#should return -1 for loss, 0 for draw, 1 for win
["OOO","XXX"].each do |f|
for i in 0..2
if (boardstate[i]+boardstate[i+3]+boardstate[i+6]).chr == f || boardstate[(3*i)..(3*i)+2] == f
return f == "OOO" ? 1 : -1
end
end
if (boardstate[0]+boardstate[4]+boardstate[8]).chr == f || (boardstate[2]+boardstate[4]+boardstate[6]).chr == f
return f == "OOO" ? 1 : -1
end
end
return 0
end
def computer_play
#Sets depth,and alpha/beta for pruning, so far so good
depth = 3
alpha = -100
beta = 100
##boardstate starts as "---------"
##active_player: 1=player, -1=computer
play(minimax(#boardstate, depth, alpha, beta, #active_player))
end
def play(array)
#Check actual boardside with parameter boardside to see what move has been
#selected and plays that move
for i in 0...array[1].length
if #boardstate[i] != array[1][i]
#color = array[1][i].chr == "X" ? #ai : #player
##cursor.y = (i / 3) * #side
##cursor.x = (i % 3) * #side
##board.bitmap.fill_rect(#cursor.x,#cursor.y,#side,#side,color)
#boardstate = array[1].dup
end
end
end
def minimax(boardstate, depth, alpha, beta, active_player)
#If bottom node reached, returns [boardstate_score, boardstate]
#wincheck returns 1 if player wins, -1 if computer wins, and 0 otherwise
if depth == 0 or wincheck(boardstate) != 0 or (/-/ =~ boardstate) == nil
return [wincheck(boardstate),boardstate]
end
if active_player == 1 #if player's turn
#Gets an array of all the next possible boardstates and return the one with
#the best eval.
child = generate_child(boardstate, active_player)
child.each do |f| #f = [Int/nil, String]
if f[0] == nil
#This should turn all the nil wincheck values to the best value of children nodes
f[0] = minimax(f[1], depth-1, alpha, beta, -active_player).last[0]
end
alpha = [f[0], alpha].max
if beta <= alpha
break
end
end
return child.sort_by{|c| c[0]}
end
if active_player == -1 #if computer's turn
#Same as above but with worst eval.
child = generate_child(boardstate, active_player)
child.each do |f|
if f[0] == nil
f[0] = minimax(f[1], depth-1, alpha, beta, -active_player).first[0]
end
beta = [f[0], beta].min
if beta <= alpha
break
end
end
#Following line raises "comparison of array with array failed" error :
return child.sort_by{|c| c[0]}
end
end
def generate_child(boardstate, active_player)
#returns boardstate string with one X or O more than current boardstate
#and sets nil as a default wincheck value
c = active_player == 1 ? "O" : "X"
a = []
for i in 0...boardstate.length
if boardstate[i].chr == "-"
s = boardstate.dup
s[i]= c
a << [nil, s]
end
end
return a
end
end
Error: comparison of array with array failed

Adding value from parent node

I am trying to implement the A* Algorithm to find the shortest path from A to B. I am using a linked list with nodes to find the best path.
One of the values I need to calculate is g, which is the cost of movement from the starting point to the current node. Moving horizontal or vertical cost 10, and moving diagonal costs 14.
For example,
11 22 33
44 55 66
Moving from 11 to 22 cost 10. From 22 to 66 cost 14, so moving from 11 to 66 cost 24 total according to that particular path.
In my node class, I have a method that calculate g from the previous node to the current node, in the previous example, 22 to 66. In order to find the total g cost, I added the g value from the parent's node. However, this is extremely expensive and takes forever to run, especially when the number of possible paths is huge.
What can I do to speed up this algorithm? Is there a better way to calculate the g value?
Here is the relevant code from my Node class.
class Node
attr_accessor :position, :g, :h, :parent
def initialize(position, parent = nil)
#position = position
#parent = parent
if parent.nil?
#g = 0
else
#g = calc_g + #parent.g #<= this line costs the issue.
end
end
def calc_h(end_pos)
(#position.first - end_pos.first).abs + (#position.last - end_pos.last).abs
end
def calc_g
row_diff = (#position.first - self.parent.position.first).abs
col_diff = (#position.last - self.parent.position.last).abs
if [row_diff, col_diff] == [1,1]
g = 14
else
g = 10
end
end
end
Here is my MazeSolver class.
require_relative 'node'
class MazeSolver
attr_accessor :open_list, :closed_list, :maze, :start_node, :end_node, :current_node
def initialize(file_name)
#open_list = []
#closed_list = {}
#maze = create_maze_array(file_name)
#start_node = Node.new(find_point("S"))
#end_node = Node.new(find_point("E"))
#current_node = #start_node
end
def create_maze_array(file_name)
maze = File.readlines(file_name).map(&:chomp)
maze.map! do |line|
line.split('')
end
maze
end
def find_point(sym)
#maze.each_with_index do |line, row|
line.each_with_index do |el, col|
return [row, col] if el == sym
end
end
end
def find_neighbors(position)
row, col = position
(row-1..row+1).each do |r|
(col-1..col+1).each do |c|
next if #closed_list.values.include?([r, c])
unless #maze[r][c] == '*'
#open_list << Node.new([r, c], #current_node)
end
end
end
#open_list
end
def solved?
#current_node.position == #end_node.position
end
def solve
until solved?
#closed_list[#current_node] = #current_node.position
find_neighbors(#current_node.position)
#current_node = lowest_f(#open_list)
#open_list.delete(#current_node)
end
path = get_path(#current_node)
display_route(path)
end
# determine the lowest f score node
def lowest_f(nodes)
f_score = {}
nodes.each do |node|
f_score[node] = node.g + node.calc_h(#end_node.position)
end
f_score.sort_by { |node, score| score }.first.first
end
# create path array
def get_path(node)
path = []
until node.position == #start_node.position
path << node.position
node = node.parent
end
path
end
# display maze without route and maze with route
def display_route(path)
display_maze
path.each do |move|
unless #maze[move.first][move.last] == 'E'
#maze[move.first][move.last] = 'X'
end
end
puts
display_maze
end
# display the maze as it is.
def display_maze
#maze.each do |line|
puts line.join
end
end
end
if __FILE__ == $PROGRAM_NAME
puts "What is the name of the maze file?"
begin
MazeSolver.new(gets.chomp).solve
rescue
puts "File does not exist. Try Again"
retry
end
end
Here is the link to repl with example mazes that I worked with. maze1.txt is the one that takes a long time to run.

How to reverse a linked list in Ruby

In the mutation example below, I don't understand how the linked list is reversed.
class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
#value = value
#next_node = next_node
end
end
def print_values(list_node)
print "#{list_node.value} --> "
if list_node.next_node.nil?
print "nil\n"
return
else
print_values(list_node.next_node)
end
end
def reverse_list(list, previous=nil)
current_head = list.next_node
list.next_node = previous
if current_head
reverse_list(current_head, list)
else
list
end
end
node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
print_values(node3)
puts "-------"
revlist = reverse_list(node3)
print_values(revlist)
If I just return current_head, I get 99->37->nil, which makes sense because 99 would be next_node. Returning the next line,
list.next_node = previous
throws an error because print_values method can't print the value for nil. I'm not understanding what is reversing the list. If anyone could explain this to me, I would appreciate it.
Here's a little visualization I made up.
^ points to head of the list. At each level of recursion, its right arrow is "turned" to point from element on the right to element on the left. Proceed until there is a right arrow (pointing to a non-nil). If right arrow points to nil, return the current head.
previous
↓
nil 12 -> 99 -> 37 -> nil
^
previous
↓
nil <- 12 99 -> 37 -> nil
^
previous
↓
nil <- 12 <- 99 37 -> nil
^
nil <- 12 <- 99 <- 37
^
# Create a LinkedListNode instance with value 36
node1 = LinkedListNode.new(37)
# Create a LinkedListNode instance which next value is node1
node2 = LinkedListNode.new(99, node1)
# node2 -> node1
# Create a LinkedListNode instance which next value is node2
node3 = LinkedListNode.new(12, node2)
# node3 -> node2 -> node1
print_values(node3)
# 12 -> 99 -> 37
Fist pass into reverse_list method
reverse_list(node3)
def reverse_list(list, previous=nil)
# set current_head to node2
current_head = list.next_node
# Change node3.next_node node2-->nil
list.next_node = previous
if current_head
# reverse_list(node2, node3)
reverse_list(current_head, list)
else
list
end
end
Second pass into reverse_list method
reverse_list(node2, node3)
def reverse_list(list, previous=nil)
# set current_head to node1
current_head = list.next_node
# Change node2.next_node node1-->node3
list.next_node = previous
if current_head
# reverse_list(node1, node2)
reverse_list(current_head, list)
else
list
end
end
last pass into reverse_list method
reverse_list(node1, node2)
def reverse_list(list, previous=nil)
# set current_head to nil
current_head = list.next_node
# Change node1.next_node nil-->node2
list.next_node = previous
if current_head
reverse_list(current_head, list)
else
# The end, return node1
list
end
end
By the way linked list is not a common practice in the ruby languages (and all the languages with a garbage collector), there is generally a class (such as Array for example) which have all the functionalities and flexibility you may need.
Here is a simple solution if someone is looking to do this without recursion
class Node
attr_accessor :value, :next
def initialize(value, next_node)
#value = value
#next = next_node
end
end
class LinkedList
attr_accessor :head, :tail
def add(value)
if(#head.nil?)
#head = Node.new(value, nil)
#tail = #head
else
#tail.next = Node.new(value, nil)
#tail = #tail.next
end
end
def reverse(list)
return nil if list.nil?
prev = nil
curr = list.head
while(curr != nil)
temp = curr.next
curr.next = prev
prev = curr
curr = temp
end
list.head = prev
list
end
def display(list)
return nil if list.nil?
curr = list.head
arr = []
while(curr != nil)
arr.push(curr.value)
curr = curr.next
end
p arr
end
end
list = LinkedList.new()
list.add(1)
list.add(2)
list.add(3)
list.display(list) #list before reversing [1,2,3]
list.display(list.reverse(list)) #list after reversing [3,2,1]

How to remove object in Ruby

I've implemented Binary search tree in ruby, and now I need to clean whole structure but I can't find any way to do that.
def post_order_clean(node)
if node.left != nil
post_order_clean(node.left)
end
if node.right != nil
post_order_clean(node.right)
end
node = nil
end
But when i do sth like that:
example = [4,6,9,5,7,3,1]
tree = BST::BinaryTree.new(example)
tree.clean
puts tree.root.value
It still prints out 4 as a root value.
How can I clean the tree with post-order traversing method?
Edit:
Just like #Cary Swoveland mentioned:
.. successively remove nodes (together with arcs directed to the node) that have no arcs directed to other nodes.
That's my point.
I did this solution for insert and remove:
class TreeNode
attr_accessor :val, :left, :right
def initialize(val)
#val = val
#left, #right = nil, nil
end
def insert(v)
side = (v <= val ? :left : :right)
if send(side)
send(side).insert(v)
else
send("#{side}=", TreeNode.new(v))
end
end
def delete(v)
if v < val
self.left = self.left ? self.left.delete(v) : nil
elsif v > val
self.right = self.right ? self.right.delete(v) : nil
else
if self.left.nil?
return self.right
elsif self.right.nil?
return self.left
end
min = self.right
min = min.left while !min.left.nil?
self.val = min.val
self.right = self.right.delete(self.val)
end
self
end
end

Having Difficulty to Understand Variables/Pointers on Ruby LinkedList Implementation

I created a singly LinkedList class with ruby.
Everything went well till trying to reverse the linked list.
It does not reverse linkedlist by this method, but when I add
#head.next = nil
after left_tmp = #head in reverse method, it just works fine.
I couldn't figure out why it works when I add that, does anyone have the explanation?
BTW I am fairly new to ruby, so please don't hesitate to tell me if there are some other things that are not "Good Practice in Ruby".
Here is classes and relevant methods:
class LlNode
attr_reader :data
attr_accessor :next
def initialize(val=nil)
#data = val
#next = nil
end
def to_s
"node_data=#{#data}"
end
end
class LinkedList
def initialize
#list = []
#head = LlNode.new
end
def insert(val)
n = LlNode.new val
# List is empty
if is_empty?
#head = n
else
n.next = #head
#head = n
end
self
end
def reverse
return if is_empty? or #head.next.nil?
curr = #head.next
right_tmp = curr.next
left_tmp = #head
while curr != nil
curr.next = left_tmp
left_tmp = curr
curr = right_tmp
right_tmp = right_tmp.next unless right_tmp.nil?
end
#head = left_tmp
end
end
When you're reversing a linked list, the first node becomes the last. In a singly-linked list, the last node's next pointer points to null. #head, which is initially your first node becomes the last. That's why you add the #head.next = nil.
Edit: Simulating a dry-run to better explain the problem
Assume two nodes in the linked list: 1->2
curr = #head.next (2)
right_tmp = curr.next (nil)
left_tmp = #head (1)
First iteration of the while loop:
curr.next = left_tmp ( 1 <-> 2)
left_tmp = curr (2)
curr = right_tmp (nil)
right_tmp = right_tmp.next unless right_tmp.nil? (nil)
There is no second iteration since curr == nil
Now:
#head = left_tmp (#head points to '2')
Final linked list state is:
1 <-> 2

Resources