JavaScript Program to Check Equal Character Frequencies
Last Updated :
06 Nov, 2023
We have given a String to ensure it has equal character frequencies, if not, equate by adding required characters and printing the final string in the console.
Example:
Input: test_str = ‘geeksforgeeks’
Output: geeksforgeeksggkkssfffooorrr
Explanation: Maximum characters are 4 of ‘e’. Other character are appended of frequency 4 – (count of chars).
Input: test_str = ‘geksforgeeks’
Output: geeksforgeeksggksffoorr
Explanation: Maximum characters are 3 of ‘e’. Other character are appended of frequency 3 – (count of chars).
These are the following approaches by using these we can solve this question:
Using JavaScript map():
In this approach, we are checking for characters in a string with the highest frequency and adjusting the string to make all characters occur with the same frequency. It utilizes methods like split, repeat, and map to find and modify characters, ensuring their frequencies are equal. The final string ‘res’ is the original string with additional characters appended to match the maximum frequency.
Example: This example shows the use of the above-explained approach.
Javascript
let test_str = 'abca' ;
console.log( "The original string is : " + test_str);
let max_freq = Math.max(...[...test_str]
.map((ele) => test_str.split(ele).length - 1));
let res = test_str;
[...test_str].forEach((chr) => {
if (res.split(chr).length - 1 !== max_freq) {
res += chr.repeat(max_freq -
(test_str.split(chr).length - 1));
}
});
console.log( "Equal character frequency String : " + res);
|
Output
The original string is : abca
Equal character frequency String : abcabc
In this approach, we are finding character with the highest frequency in a string and ensures all characters appear with the same frequency. It uses the split and reduce methods to count character occurrences, and Math.max to find the maximum frequency. The code then adjusts the string to match the highest frequency, resulting in the modified string res.
Example: This example shows the use of the above-explained approach.
Javascript
let test_str = 'abcaa' ;
console.log( "The original string is : " + test_str);
let freq_dict =
test_str.split( '' ).reduce((acc, curr) => {
acc[curr] = (acc[curr] || 0) + 1;
return acc;
}, {});
let max_freq = Math.max(...Object.values(freq_dict));
let res = test_str;
[...test_str].forEach((chr) => {
if (res.split(chr).length - 1 !== max_freq) {
res += chr.repeat(max_freq
- (test_str.split(chr).length - 1));
}
});
console.log( "Equal character frequency String : " + res);
|
Output
The original string is : abcaa
Equal character frequency String : abcaabbcc
Share your thoughts in the comments
Please Login to comment...