// C# program to implement above approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
// Function to find frequency in 3-D matrix
static void findFreq(int X, int Y, int Z,
char[][][] matrix)
{
// Initializing unordered map
Dictionary<char, int> freq = new Dictionary<char, int>();
for (int i = 0 ; i < X ; i++) {
for (int j = 0 ; j < Y ; j++) {
for (int k = 0 ; k < Z ; k++) {
if (!freq.ContainsKey(matrix[i][j][k])){
freq.Add(matrix[i][j][k], 1);
}else{
freq[(matrix[i][j][k])] += 1;
}
}
}
}
// Get the size of the freq hashmap
// to declare a new array
int size = freq.Count;
// Store the frequency in 2d array v
pair[] v = new pair[size];
for(int i = 0 ; i < size ; i++){
v[i] = new pair(0, 0);
}
int index = 0;
foreach (KeyValuePair<char, int> mapElement in freq){
v[index].first = (int)mapElement.Key;
v[index].second = mapElement.Value;
index++;
}
// Sort the frequency array
// based on the frequencies
Array.Sort(v, new Comp());
for (int i = 0; i < size; i++) {
Console.WriteLine((char)v[i].first + " " + v[i].second);
}
}
public static void Main(string[] args){
// Drivers code
int X = 3, Y = 4, Z = 5;
// Declare 3D array of characters
char[][][] matrix = new char[][][]{
new char[][]{
new char[]{ 'a', 'b', 'c', 'd', 'e' },
new char[]{ 'f', 'g', 'h', 'i', 'k' },
new char[]{ 'a', 'c', 'd', 'e', 's' },
new char[]{ 'e', 'g', 'e', 's', 'j' }
},
new char[][]{
new char[]{ 's', 'j', 'r', 's', 'g' },
new char[]{ 's', 't', 'u', 'e', 'y' },
new char[]{ 't', 'y', 'g', 'j', 'l' },
new char[]{ 'd', 'r', 'g', 't', 'j' }
},
new char[][]{
new char[]{ 'e', 'y', 'r', 'v', 'n' },
new char[]{ 'q', 'r', 'y', 'e', 'w' },
new char[]{ 'k', 'e', 'u', 'p', 'q' },
new char[]{ 'z', 'v', 'a', 's', 'd' }
}
};
// Function call
findFreq(X, Y, Z, matrix);
}
}
// Class for pair
public class pair{
public int first;
public int second;
// Constructor
public pair(int f, int s)
{
this.first = f;
this.second = s;
}
}
class Comp : IComparer<pair>{
public int Compare(pair a, pair b)
{
if(a.second == b.second){
return a.first-b.first;
}
return a.second-b.second;
}
}
// This code is contributed by subhamgoyal2014.