Find the frequency of each element in an array in swift

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

import Foundation
class Occurrence
{
	// Function which is display array elements
	static func display(_ arr: [Int])
	{
		var i: Int = 0;
		while (i < arr.count)
		{
			print(" ", arr[i], terminator: " ");
			i += 1;
		}
		print(terminator:"\n");
	}
	// Count occurrence of given array
	static func frequency(_ arr: [Int])
	{
		// Display given array
		Occurrence.display(arr);
		// Create a empty map
		var map: [Int: Int] = [Int: Int]();
		
		for data in arr
		{
			if (map.keys.contains(data))
			{
				// When key exists then update value
				map[data] = map[data]! + 1;
			}
			else
			{
				// Add new element
				map[data] = 1;
			}
			
		}
		print(" Occurrence ");
		//  Display calculated result
		for key in Array(map.keys)
		{
			print(" ",key, " : ",map[key]!);
		}
	}
	static func main(_ args: [String])
	{
		// Array element
		let arr: [Int] = [1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7];
		Occurrence.frequency(arr);
	}
}
Occurrence.main([String]());

Output

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


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







© 2021, kalkicode.com, All rights reserved