same frequency

Run Settings
LanguageJavaScript
Language Version
Run Command
/* Write a function checking that the given string is valid. We consider a string to be valid if all the characters of the string have exactly the same frequency. Examples: "aabbcc" is a valid string "aabbccc" is an invalid string "ababab" is a valid string */ /* abcabc -> is valid char only "abababab" -> is valid "ababab" -> is valid "abcab" -> is invaild "" -> valid */ /* - Dic for all a-z char + asci chars - loop in string to fill this [] with count of every char - loop at dic check all items have same count - * count - * define maxChange = 1 - * if count !== (count C) -if not -> maxChange > 0) maxChange <- 0 - add null or empty is valid - return true /false */ /* tests abcabc -> is valid "abababab" -> is valid "ababab" -> is valid "abcab" -> is invaild "" -> valid "AbAb" -> valid "@b@b" -> valid "1b1b" -> valid "Aa" -> invalid */ /* Check if the string is valid as it is (same condition as before) or if one character at one position can be removed from the string so it will become valid. "aabbcc" is a valid string "aaabbcc" is a valid string "arrrttt" => 3 "aaaarrrrttt" => 4 */ const _ = require('lodash'); let validFrequency = (input) => { if(!input) return true; function fillMapByCharCount() { let map = new Map(); for(let i=0;i<input.length;i++){ map.set(input[i], map.has(input[i]) ? (map.get(input[i])+1) : 1); } return map; } function mostFrequent(map){ let mapCount = new Map(); map.forEach((value,key) => { mapCount.set(value, mapCount.has(value) ? (mapCount.get(value)+1) : 1); }); let count = -1, maxCount=0; mapCount.forEach((value,key) => { if(maxCount < value){ maxCount = value; count = key; } }); return count; } function compareNumbers(map,count,maxChange){ let result = true; map.forEach((value,key) => { if(value !== count) { //console.log(value + " : " + count + " " + maxChange) if(maxChange>0) maxChange--; else result = false; } }); return result; } let map = fillMapByCharCount(); return compareNumbers( map, mostFrequent(map), 1); } _.times(1, console.log( validFrequency("22333444")) );
Editor Settings
Theme
Key bindings
Full width
Lines