Skip to main content

Find the frequency of each element in an array in ruby

Ruby program for Find the frequency of each element in an array. Here problem description and other solutions.

class Occurrence 
	#  Function which is display array elements
	def display(arr) 
		i = 0
		while (i < arr.length) 
			print("   ", arr[i])
			i += 1
		end
		print("\n")
	end

	#  Count occurrence of given array
	def frequency(arr) 
		#  Display given array
		self.display(arr)
		#  Create a empty map
		map = Hash.new()
		i = 0
		while (i < arr.length) 
			if (map.key?(arr[i])) 
				#  When key exists then update value
				map[arr[i]] = map[arr[i]] + 1
			else
 
				#  Add new element
				map[arr[i]] = 1
			end

			i += 1
		end

		print("  Occurrence ", "\n")
		#   Display calculated result
		map.each { | key, value | 
          print("  ", key ,"  :  ", value, "\n")
		}
	end

end

def main() 
	#  Array element
	arr = [1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7]
	obj = Occurrence.new()
	obj.frequency(arr)
end

main()

Output

   1   3   2   1   4   2   7   9   1   3   3   4   7
  Occurrence 
  1  :  3
  3  :  3
  2  :  2
  4  :  2
  7  :  2
  9  :  1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment