I want to get the count of various strings stored in different files. Actually I need two types of counts. For a string str,
1.) Total no of occurrences of the string str throughout all the files. 2.) Number of files having the string str.
Below is my RUBY Code for it in which i have managed to get the total count. But i can't get the file count. I have used arrays instead of files for simplicity(analogous to files) and an instance variable 'flag'.
My concept is that if flag = 0, it means the string is encountered for the first time in the first array. So the filecount(or arraycount in this case) is incremented and flag is set to 1. So when the same string appears in the same array , flag is already set to 1 and nothing happens. When an array is over, all the flag values are set back to 0.(I think so)
But something's not working as expected. Thanks in Advance..!
class Tree
attr_accessor :left
attr_accessor :right
attr_accessor :data
attr_accessor :count
attr_accessor :flag
attr_accessor :howmanyfiles
def initialize(x=nil)
@left = nil
@right = nil
@data = x
@count = 1
@flag = 0
@howmanyfiles = 1
end
def search(x)
if self.data == x
self.count = self.count + 1
if self.flag == 0
self.howmanyfiles = self.howmanyfiles + 1
end
return "#{self.data} found" #self
else
ltree = left != nil ? left.search(x) : nil
return ltree if ltree != nil
rtree = right != nil ? right.search(x) : nil
return rtree if rtree != nil
end
nil
end
def insert(x)
list = []
if @data == nil
@data = x
self.flag = 1
elsif @left == nil
@left = Tree.new(x)
self.flag = 1
elsif @right == nil
@right = Tree.new(x)
self.flag = 1
else
list << @left
list << @right
loop do
node = list.shift
if node.left == nil
node.insert(x)
break
else
list << node.left
end
if node.right == nil
node.insert(x)
break
else
list << node.right
end
end
end
end
def traverse()
list = []
yield @data
list << @left if @left != nil
list << @right if @right != nil
loop do
break if list.empty?
node = list.shift
yield node.data
list << node.left if node.left != nil
list << node.right if node.right != nil
end
end
end
items = ["Amal","Hai", "Bob", "Bob", "Cat", "Cat", "Amal", "Dog", "Rizu", "Zol","Amal"]
tree = Tree.new
items.each {|x|
if tree.search(x) == nil
tree.insert(x)
end}
ObjectSpace.each_object(Tree) do |obj|
obj.flag = 0
end
items1 = ["Amal","wet", "jjj", "Cat"]
items1.each {|x|
if tree.search(x) == nil
tree.insert(x)
end}
ObjectSpace.each_object(Tree) do |obj|
obj.flag = 0
end
items2 = ["aa","Amal", "jjj"]
items2.each {|x|
if tree.search(x) == nil
tree.insert(x)
end}
ObjectSpace.each_object(Tree) do |obj|
puts obj.data.to_s + " " + obj.count.to_s + " " + obj.howmanyfiles.to_s
end
tree.traverse {|x| print "#{x} "}
print "\n"
Aucun commentaire:
Enregistrer un commentaire