Using Dictionary:
string input = "Mahindra Thar Armada";
Dictionary charFrequency = new Dictionary();
foreach (char c in input)
{
if (charFrequency.ContainsKey(c))
{
charFrequency[c]++;
}
else
{
charFrequency[c] = 1;
}
}
// Print the character frequencies
foreach (var pair in charFrequency)
{
Console.WriteLine($"{pair.Key} - {pair.Value}");
}
Using Linq Query:
var charFrequency = input
.GroupBy(c => c)
.ToDictionary(g => g.Key, g => g.Count());
// Print the character frequencies
foreach (var pair in charFrequency)
{
Console.WriteLine($"{pair.Key} - {pair.Value}");
}
Using JavaScript
const frequencyOfChar = (arr) => {
return arr.reduce((total, letter) => {
total[letter] ? total[letter]++ : (total[letter] = 1);
return total;
}, {});
};
let input="Mahindra Thar Armada";
let arr=[...input];
const result = frequencyOfChar(arr);
console.log(result); // {"M": 1,"a": 5,"h": 2, "i": 1, "n": 1, "d": 2, "r": 3, " ": 2, "T": 1, "A": 1, "m": 1 }
No comments :
Post a Comment