Skip to content

Instantly share code, notes, and snippets.

@davingee
Created June 24, 2016 19:49
Show Gist options
  • Save davingee/e340d86c45ff18574e8b85700dd4c17a to your computer and use it in GitHub Desktop.
Save davingee/e340d86c45ff18574e8b85700dd4c17a to your computer and use it in GitHub Desktop.
# You are being asked to implement classes to manage a tree of nodes. This should be done in Ruby.
class TreeNode
attr_accessor :value, :key, :children
def initialize( args = {} )
self.value = args.fetch(:value, 1)
self.key = args.fetch(:key, 'abandoned')
self.children = args.fetch(:children, {})
end
# 1. Implement a TreeNode class. This class should have a string key along with an integer value.
# TreeNodes are considered equivalent when their keys are equivalent.
# A given TreeNode can also have one or more children TreeNodes.
# The order of the children doesn't matter, but a parent TreeNode can have only one child with a given key.
def self.create_node( args = {} )
TreeNode.new( args )
end
end
class NodeManager
attr_accessor :root_node
def initialize( args = {} )
self.root_node = args[ :root_node ] || TreeNode.create_node( value: 1, key: :root )
end
def add( node, tree_level_to_modify )
end
def remove( node, tree_level_to_modify )
end
def self.init( args = {} )
NodeManager.new( root_node: args[:node] )
end
# 2. Implement a NodeManager class. It contains a single TreeNode, which is the root of a tree. This class should have two methods:
end
node_1 = TreeNode.create_node(value: 1, key: :root)
manager = NodeManager.init
manager.add()
node_1.children[:child1] = TreeNode.create_node(value: 1, key: :child1)
# a. add(node, tree_level_to_modify) (node is a TreeNode, and tree_level_to_modify is an integer);
# this method will update all nodes in the tree which equal the TreeNode by adding the value of the passed node to the value of the existing node.
# It will only modify nodes which are at the specified tree_level_to_modify (0 refers to the root).
#
# b. remove(node, tree_level_to_modify) (node is a TreeNode, and tree_level_to_modify is an integer);
# this method will remove all nodes in the tree at the specified level whose value equals the value of node.
#
# Note that a given NodeManager and its nodes might be used by multiple threads.
# Both classes should be written to support sharing between threads.
#
# (We almost never write shared-memory threaded code, but it's important we see you are able to do it.)
class Foo
def self.bar
@bar ||= create_no
end
def self.create_no
no = rand(10000)
sleep 1
no
end
end
10.times.map do
Thread.new do
puts "bar is #{Foo.bar}"
end
end.each(&:join)
class Foo
@mutex = Mutex.new
def self.bar
@mutex.synchronize {
@bar ||= create_no
}
end
def self.create_no
no = rand(10000)
sleep 1
no
end
end
10.times.map do
Thread.new do
puts "bar is #{Foo.bar}"
end
end.each(&:join)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment