I need to calculate pairs of same letters that stay each other in twos, I got this code
const calculateLetters = (text: string) => {
const arrayStr = [...text];
let count = 0;
for (let i = 0; i < arrayStr.length; i++) {
if (arrayStr[i] === arrayStr[i + 1]) {
count += 1;
}
}
return count;
};
console.log(calculateLetters('ABBAAA'));
But now it returns 3, what I need to do is make count equal 2, because I need to calculate pairs of same letters.
In your if statement, if you've found a pair, then iterate till the point your i+1th element is not same as ith element, and then count again.
You can accomplish this with RegEx The below pattern will count matches of the same character pairs.
const countPairs = (text) => {
//Grab the matches length if any exist, otherwise return 0
return (text.match(/(.)\1/g))?.length ?? 0
}
console.log(countPairs("abc")) //Result is 0
console.log(countPairs("ABBAAA")) //Result is 2
console.log(countPairs("aabBccDD111")) //Result is 4
With your code, you just need to move past the match when you find one
const calculateLetters = (text) => {
const arrayStr = [...text];
let count = 0;
for (let i = 0; i < arrayStr.length; i++) {
if (arrayStr[i] === arrayStr[i + 1]) {
count += 1;
//move past the match
i++;
}
}
return count;
};
console.log(calculateLetters('ABBAAA'));
const calculateLetters = (text: string) => {
const arrayStr = [...text];
let count = 0;
for (let i = 0; i < arrayStr.length; i++) {
let j = i;
while(i + 1 < arrayStr.length && arrayStr[i] === arrayStr[i + 1]) {
i+= 1;
}
if(i != j){
count += 1;
}
}
return count;
};
console.log(calculateLetters('ABBAAA'));
Define a zip function that can be used to create a list of pairs of adjacent letters in the text. Then count the pairs that match.
Since you want unique adjacent letters, pass the pairs through a Set before counting.
const zip = (a, b) => a.map((k, i) => [k, b[i]])
const calculateLetters = (text) => {
const chars = [...text]
const adjacentLetters = zip(chars, chars.slice(1))
const uniqueAdjacentLetters = [
...new Set(adjacentLetters.map(([a,b]) => `${a}:${b}`))
].map(x => x.split(':'))
const count = uniqueAdjacentLetters.reduce(
(total, [a,b]) => total + ((a === b) ? 1 : 0),
0,
)
return count
}
console.log(calculateLetters('ABBAAA'))
Related
i have a task:
Count the number of letters “a” in text
Count the number of letters “o” in text
Write the result of multiplying the number of letters “a” and “o”.
is it possible to solve this task in a shorter way??
function countString(str, letter) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) == letter) {
count += 1;
}
}
return count;
}
const string = hello my name is Ola.toLowerCase()
const letterToCheck = "o"
const letterToCheckTwo = "a"
const result = countString(string, letterToCheck);
const resultTwo = countString(string, letterToCheckTwo);
const total = result + resultTwo
console.log(total)
With regular expression function match() will output all the matched conditions.
const string = "hello my name is Ola"
const numberOfA = string.match(/a/gi);
const numberOfO = string.match(/o/gi);
console.log(numberOfA.length * numberOfO.length)
you can do something like this using map filter and reduce
const calculate = (string, letters) => letters
.map(l => string.split('').filter(c => c === l).length)
.reduce((res, item) => res * item)
const string = 'hello my name is Ola'.toLowerCase()
console.log(calculate(string, ['a', 'o']))
console.log(calculate(string, ['a', 'o', 'e']))
You can create an object that stores the count of all the characters and then you can compute the product using this object.
const str = "Avacado";
const charsCount = Array.prototype.reduce.call(
str,
(r, ch) => {
const lowerCh = ch.toLowerCase()
r[lowerCh] ??= r[lowerCh] || 0;
r[lowerCh] += 1;
return r;
},
{}
);
console.log(charsCount["o"] * charsCount["a"]);
Note: Array.prototype.reduce is a generic method, so it can be used with a string as well.
There are a few different approaches. In this post I've programmed in a way that allows you to expand to different letters, different amounts of letters, and different strings easily. There may be better approaches if your problem never needs to change.
In your current code, your are traversing the strings twice and counting the occurrences of the letter within them. You could easily pass the function an array and only traverse the string once:
function countString(str, letters) {
//rather than being a character, letter is now an array of characters
let count = 0;
for (let i = 0; i < str.length; i++) {
if (letters.includes(str.charAt(i))) {
count += 1;
}
}
return count;
}
const string = "hello my name is " + Ola.toLowerCase()
const lettersToCheck = ["o", "a"]
const result = countString(string, lettersToCheck);
//iterate over the array to get the total
var product = 1;
for (int i = 0; i < result.length; i++){
product *= result[i];
}
console.log(product);
Rather than iterating over the strings, however, a different approach is to use regular expressions and .match(). This approach has fewer iterations, although I'm not sure about the low level efficiency, since lots of the comparison is encapsulated by .match():
function countString(str, letters) {
//iterates over the array of letters rather than the string
for (var i = 0; i < letters.length; i++){
count += (str.match(new RegExp(letters[i], "g")) || []).length;
}
return count;
}
const string = "hello my name is " + Ola.toLowerCase()
const lettersToCheck = ["o", "a"]
const result = countString(string, lettersToCheck);
//iterate over the array to get the total
var product = 1;
for (int i = 0; i < result.length; i++){
product *= result[i];
}
console.log(product);
If regex is too much, you could also use .split() to iterate over the characters rather than the string:
function countString(str, letters) {
//iterates over the array of letters rather than the string
for (var i = 0; i < letters.length; i++){
count += str.split(letters[i]).length - 1;
}
return count;
}
const string = "hello my name is " + Ola.toLowerCase()
const lettersToCheck = ["o", "a"]
const result = countString(string, lettersToCheck);
//iterate over the array to get the total
var product = 1;
for (int i = 0; i < result.length; i++){
product *= result[i];
}
console.log(product);
See this post for more information
You can compute the letter frequency each time the phrase changes and then request the product by specifying the letters in the frequency map.
const letterFrequencyMap = (str) =>
str.toLowerCase().split('').reduce((acc, k) =>
acc.set(k, (acc.get(k) ?? 0) + 1), new Map);
const computeProduct = (freq, ...keys) =>
keys.reduce((product, k) => product * (freq.get(k) ?? 1), 1);
// Main
const phrase = "It's about to be noon in a bit.";
const freq = letterFrequencyMap(phrase);
// a = 2; o = 4
console.log(computeProduct(freq, 'a', 'o')); // 8
I am trying to place three strings into an array size of 9 that holds them three string placed at random indexes in the array but how I am trying to do it is resulting in an infinite loop
const ticketArray = [];
const victoryMultipliers = ["x10", "x20", "x30", "x40", "x50", "x60"];
const threeOfThem = [];
let arr = []
let randStr = "";
for (let i = 0; i < 3; i++) {
threeOfThem[i] = victoryMultipliers[Math.floor(Math.random() * victoryMultipliers.length)]
randStr = threeOfThem[i]
//console.log(randStr)
arr = threeOfThem.filter(val => val === randStr)
if (arr.length >= 2) {
threeOfThem.pop();
i--;
}
}
const threeTicketArray = threeOfThem;
/// So above we have an array of example ["x20", "x50", "x30"]
// so below is where we have some problem
let randInt;
let tempStr = "";
for (let i = 0; i < 10; i++) { // i want to make an array.length of 9
randInt = Math.floor( Math.random() * 3 );
tempStr = threeTicketArray[randInt]; // to find the "x30" or whichever i stored
ticketArray.push(tempStr); // push it into the ticketArray
let len = ticketArray.filter(val => val === tempStr) // we filter to bring out the once for this loops iteration
if ( len.length > 3 ) { // if I have 4 of example "x30"
ticketArray.pop(); // I remove it as it was the last "x30" string added to the array
i--; // I subtract the iteration by 1 so I can restart the this iteration of the loop
}
}
// the end of the loop
console.log(ticketArray);
So at random I want ticketArray to be of size 9 the ticket strings to be placed at a random index and each string appears 3 times. However, I am getting an infinite loop I can't understand why!
See the solution below, and tell me what you think
const ticketArray = [];
const victoryMultipliers = ["x10", "x20", "x30", "x40", "x50", "x60"];
const threeOfThem = [];
let arr = []
let randStr = "";
for (let i = 0; i < 3; i++) {
threeOfThem[i] = victoryMultipliers[Math.floor(Math.random() * victoryMultipliers.length)]
randStr = threeOfThem[i]
//console.log(randStr)
arr = threeOfThem.filter(val => val === randStr)
if (arr.length >= 2) {
threeOfThem.pop();
i--;
}
}
const threeTicketArray = threeOfThem;
/// So above we have an array of example ["x20", "x50", "x30"]
// so below is where we have some problem
let randInt;
let tempStr = "";
for (let i = 0; i < 10; i++) { // i want to make an array.length of 9
randInt = Math.floor( Math.random() * 3 );
tempStr = threeTicketArray[randInt]; // to find the "x30" or whichever i stored
ticketArray.push(tempStr); // push it into the ticketArray
let len = ticketArray.filter(val => val === tempStr) // we filter to bring out the once for this loops iteration
if ( len.length > 3 ) { // if I have 4 of example "x30"
ticketArray.pop();
// this should solve the infinit loop issue.
// as it seems that randInt is generating duplicated.
if (ticketArray.length <9)
i--
}
}
// the end of the loop
console.log(ticketArray);
You can do:
const victoryMultipliers = ["x10", "x20", "x30", "x40", "x50", "x60"]
const vmCopy = [...victoryMultipliers]
const randomVM = arr => arr
.splice(Math.floor(Math.random() * arr.length), 1)
.pop()
const ticketArray = [...Array(3)]
.map(() => randomVM(vmCopy))
.reduce((a, c, i, arr) => a.concat(arr), [])
.map(v => ({ v, s: Math.random() }))
.sort((a, b) => a.s - b.s)
.map(({ v }) => v)
console.log(ticketArray)
I have an array of numbers. I need to find the maximum number of consecutive 1s in the array.
var arr = [1, 1, 3, 2, 3, 1, 1, 1];
const maxOne = (arr) => {
for (var i = 0; i < arr.length; i++) {
let count = 0;
let result = 0;
if (arr[i] ==1) {
count += 1;
result = Math.max(result, count);
} else {
count = 0
}
return result
}
}
console.log(maxOne(arr));
desired output: 3
my output : 1
I am not sure where I am going wrong
You algorithm works, you just did few misstakes:
create variables outside of loop
return after loop, not in it(it will break loop at first iteration)
const maxOne = (arr) => {
let count = 0;
let result = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === 1) {
count += 1;
result = Math.max(result, count);
} else {
count = 0
}
}
return result
}
You can do like this.
let arr=[1,2,3,1,1,2,1,1,12,1,1,1,1];
let count=0;
for(let i=0;i<arr.length;i++){
arr[i]==1 ? count+=1 :count=0;
}
console.log(count).
const numbers = [1,1,0,0,1,1,1,0,1];
const maxString = Math.max(...numbers.join('').split('0')); // remove zero items and convert
// the sequential Ones to a string. After that Find the string with the largest number of characters.
console.log('max:', maxString.toString().length) // Take the string length
//3
you can use *Math.max.apply(Math, numbers.join('').split('0'))* instead of second line.
Question: Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
12 ==> 21
513 ==> 531
2017 ==> 2071
//nextBigger(num: 12) // returns 21
//nextBigger(num: 513) // returns 531
//nextBigger(num: 2017) // returns 2071
I am trying to compare two Array and get correct array as answer. In do...while loop I am comparing the two array by increment second array by one.
function nextBigger(n){
let nStrg = n.toString();
let nArr = nStrg.split('');
function compareArr(Ar1,Ar2){
if(Ar2.length>Ar1.length){
return false;
}
for(let i=0; i<Ar1.length; i++){
let num = Ar1[i];
for(let j=0; j<Ar2.length; j++){
if(Ar2.lastIndexOf(num) !== -1){
Ar2.splice(Ar2.lastIndexOf(num), 1);
break;
}
else{
return false;
break;
}
}
}
return true;
}
let nextNumArr;
let m = n;
do{
let nextNum = m+1
m=nextNum
let nextNumStrg = nextNum.toString();
nextNumArr = nextNumStrg.split('')
console.log(compareArr(nArr, nextNumArr))
}
while(compareArr(nArr, nextNumArr) == false)
console.log(nextNumArr)
return parseInt(nextNumArr.join())
}
nextBigger(12);
This gives me empty array at the end;
[2,0,1,7].join() will give you '2,0,1,7', can use [2,0,1,7].join('') and get '2017'
All looks a bit complicated. How about:
const nextLarger = num => {
const numX = `${num}`.split(``).map(Number).reverse();
for (let i = 0; i < numX.length; i += 1) {
if ( numX[i] > numX[i + 1] ) {
numX.splice(i, 2, ...[numX[i+1], numX[i]]);
return +(numX.reverse().join(``));
}
}
return num;
};
const test = [...Array(100)].map(v => {
const someNr = Math.floor(10 + Math.random() * 100000);
const next = nextLarger(someNr);
return `${someNr} => ${
next === someNr ? `not possible` : next}`;
}).join('\n');
document.querySelector(`pre`).textContent = test;
<pre></pre>
See also
function nextbig(number) {
let nums = []
number.toString().split('').forEach((num) => {
nums.push(parseInt(num))
})
number = nums
n = number.length
for (var i = n - 1; i >= 0; i--) {
if (number[i] > number[i - 1])
break;
}
if (i == 1 && number[i] <= number[i - 1]) {
return 'No greater possible'
}
let x = number[i - 1];
let smallest = i;
for (let j = i + 1; j < n; j++) {
if (number[j] > x &&
number[j] < number[smallest])
smallest = j;
}
let temp = number[smallest];
number[smallest] = number[i - 1];
number[i - 1] = temp;
x = 0
for (let j = 0; j < i; j++)
x = x * 10 + number[j];
number = number.slice(i, number.length + 1);
number.sort()
for (let j = 0; j < n - i; j++)
x = x * 10 + number[j];
return x
}
console.log(nextbig(12))
console.log(nextbig(513))
console.log(nextbig(2017))
In compareArr you are deleting elements as you find them, which is correct to do, to make sure duplicates actually occur twice etc. However, that also deletes the elements from nextNumArr in the calling context, because the array is passed by reference and not by value. You need to do a manual copy of it, for example like this: compareArr(nArr, [...nextNumArr]).
I have used a different approach, first I search for all possible combinations of the given numbers with the permutator function. This function returns an array of possible numbers.
Then I sort this array of combinations and look for the index of the given number in the main function.
Once I have this index I return the position before the given number.
function nextbig(num){
function permutator(inputArr){
let result = [];
const permute = (arr, m = []) => {
if (arr.length === 0) {
result.push(m)
} else {
for (let i = 0; i < arr.length; i++) {
let curr = arr.slice();
let next = curr.splice(i, 1);
permute(curr.slice(), m.concat(next))
}
}
}
permute(inputArr)
return result;
}
let arrNums = num.toString().split('')
let combinations = permutator(arrNums).map(elem => parseInt(elem.join("")))
combinations.sort((a, b) => {
return b - a
})
let indexOfNum = combinations.findIndex(elem => elem === num)
let nextBigIndex = indexOfNum <= 0 ? 0 : indexOfNum - 1
return (combinations[nextBigIndex])
}
console.log(nextbig(12))
console.log(nextbig(517))
console.log(nextbig(2017))
Assuming I have the following string "355385". I need a simple JavaScript that can tell me that the most mentioned character is 5. Thank you in advance.
I tried with this one but no results.
var exp = '355385' ;
var exps =exp.split("");
var expCounts = { };
for (var i=0;i<exp.length;i++)
{expCounts["_" + exps[i]] = (expCounts["_" + exps[i]] || 0) + 1 ;
if (expCounts==3) exps=exps[i]; }; exps;
This will loop over every character in the string and keep track of each character's count and the character with the maximum count:
var exp = '3553853335' ;
var expCounts = {};
var maxKey = '';
for(var i = 0; i < exp.length; i++)
{
var key = exp[i];
if(!expCounts[key]){
expCounts[key] = 0;
}
expCounts[key]++;
if(maxKey == '' || expCounts[key] > expCounts[maxKey]){
maxKey = key;
}
}
console.debug(maxKey + ":" + expCounts[maxKey]);
Update:
Here is an ES6 version that will handle strings where multiple character have the same max count
function maxCount(input) {
const {max, ...counts} = (input || "").split("").reduce(
(a, c) => {
a[c] = a[c] ? a[c] + 1 : 1;
a.max = a.max < a[c] ? a[c] : a.max;
return a;
},
{ max: 0 }
);
return Object.entries(counts).filter(([k, v]) => v === max);
}
Example (please excuse the crude output):
maxCount('--aaaa1111--').join(' | ').replace(/,/g, ':');
outputs 1:4 | -:4 | a:4
var getMax = function (str) {
var max = 0,
maxChar = '';
str.split('').forEach(function(char){
if(str.split(char).length > max) {
max = str.split(char).length;
maxChar = char;
}
});
return maxChar;
};
logs
getMax('355385') //5;
getMax('35538533') //3;
in equal case it will return first number
getMax('3553') //3;
var string = "355385",
counter = {};
for (var i = 0, len = string.length; i < len; i += 1) {
counter[string[i]] = (counter[string[i]] || 0) + 1;
}
var biggest = -1, number;
for (var key in counter) {
if (counter[key] > biggest) {
biggest = counter[key];
number = key;
}
}
console.log(number);
# 5
var exp = '355385';
var findMostFrequent = function (string) {
var chars = {}, first = string.charAt(0);
chars[first] = 1;
var maxChar = first, maxCount = 1;
for (var i = 1; i < string.length; i++) {
var char = string.charAt(i);
if (chars[char]) {
chars[char]++;
} else {
chars[char] = 1;
}
if (chars[char] > maxCount) {
maxChar = char;
}
}
return maxChar;
};
Another Solution
function maxChar(str) {
const charMap = {};
let max = 0;
let maxChar = '';
for(let char of str){
if(charMap[char]){
charMap[char]++;
}else{
charMap[char] = 1;
}
}
for(let char in charMap){
if(charMap[char] > max){
max = charMap[char];
maxChar = char;
}
}
return maxChar;
}
Result:
maxChar('355385')
"5"
Another way to get the most frequent character in a string - sort frequency map into an array and then return the first (greatest) value from that array:
function highest (string) {
let array = Array.from(string);
let frequencyMap = {};
array.forEach((value, index) => {
if (!frequencyMap[value]) {
frequencyMap[value] = 0;
}
frequencyMap[value] += 1;
})
let frequencyArray = Object.entries(frequencyMap);
frequencyArray.sort((a, b) => {
if (a[1] < b[1]) {
return 1;
}
if (a[1] > b[1]) {
return -1;
}
return 0;
});
return(frequencyArray[0][0]);
}
console.log(highest("hello World"));
returns "l"
None of the answers above take into consideration that JavaScript internally uses UTF-16
const s = "😄😅😄😄😅😅😄😄😱😱😄";
function getMostFrequentChar(s) {
const len = s.length;
const freq = {};
let maxFreq = 0;
let maxChar;
for (let i = 0; i < len; ++i) {
const isPair = (s.charCodeAt(i) & 0xF800) == 0xD800;
const c = isPair ? s.substr(i++, 2) : s[i];
const f = (freq[c] || 0) + 1;
freq[c] = f;
if (f > maxFreq) {
maxFreq = f;
maxChar = c;
}
}
return {maxFreq, maxChar, freq}
}
console.log(getMostFrequentChar(s));
Note: the code above assumes the string is valid UTF-16. It's possible to construct a string that is not valid UTF-16 in which case maybe you could change isPair to
const isPair = len - i > 1 &&
s.charCodeAt(i ) & 0xF800) == 0xD800 &&
s.charCodeAt(i + 1) & 0xF800) == 0xD800;
But it's not clear what a character with an invalid UTF-16 value means.
It also won't handle more funky unicode
s = "👦🏿👦👦🏿👦👦🏻👦🏽👦🏾👦🏿"
There are many graphmemes that take multiple unicode code points
Also, splitting the string using split is SSSSSSLLLLLOOOOWWWW and a huge memory hog if the string is long.
Here is yet another answer to this question:
For this I have considered that the character can be of whatevert kind except a space
function findHighestFreqInString(str) {
if (!str) return null
let cleanedStr = str.replace(/\s/g, '') //assumes no spaces needed
if (cleanedStr.length === 0) return null
let strObj = {}
let topChar = ''
for (let val of cleanedStr) {
strObj[val] = (strObj[val] || 0) + 1
if (topChar === '' || strObj[val] >= strObj[topChar]) topChar = val
}
return topChar
}
Here is how you would use it:
findHighestFreqInString('my name is Someone') // returns: e
findHighestFreqInString('') // returns: Null
findHighestFreqInString(' ') // returns: Null
Here is:
let str = '355385';
function mostFrequentCharacter(str) {
let charactersArr = str.split(''),
bins = {};
charactersArr.map(el => bins[el] = (bins[el] || 0) + 1);
return Object.keys(bins).map(key => ({
name: key,
count: bins[key]
})).sort((a, b) => b.count - a.count)[0];
}
You can use the following solution to find the most frequent character in a string:
function getMostRepeatedCharacter(string) {
return string.split('').reduce((acc,char)=>{
let len = string.split(char).length - 1;
return len > acc[1] ? [char,len] : acc
},['',0])[0]
}
getMostRepeatedCharacter('wediuaududddd') // d
Want to share this ES6 functional approach. Please provide your input.
function maxChar(myStr) {
let charObj = {};
return [...myStr].reduce((_, char) => {
if (char in charObj) charObj[char]++;
else if (char !== " ") charObj[char] = 1;
return Object.keys(charObj).reduce((a, b) => {
return charObj[a] > charObj[b] ? a : b;
});
});
}
The simplest approach will be like this:
function maxChar(str) {
const charMap = {};
let max = 0;
let maxChar = '';
start by making an object of words and how many they repeated, to do that we have to loop through the string using for of and implementing the conditions:
for (let char of str) {
if (charMap[char]) {
charMap[char]++;
} else {
charMap[char] = 1;
}
}
and now loop through the object using for in
for (let char in charMap) {
if (charMap[char] > max) {
max = charMap[char];
maxChar = char;
}
}
return maxChar;
}
this is another (bizarre) way
It substitute the current character with blank for check how many times is present in the string making the difference of length with original pattern
var str = "355385";
var mostLength = 0;
var characterMostLength;
for(t = 0; t< 10; t++)
{
var res = str.length - str.replace(new RegExp(t, "g"), "").length;
if (res > mostLength){
characterMostLength = t;
mostLength = res;
}
}
function solution(N) {
var textToArr = N.split('');
var newObj = {};
var newArr = [];
textToArr.map((letter) => {
if(letter in newObj){
newObj[letter] = newObj[letter]+1;
} else {
if(letter !== ' '){
newObj = Object.assign(newObj, {[letter]: 1})
}
}
});
for(let i in newObj){
newArr.push({name: i, value: newObj[i]})
}
var res = newArr.sort((a,b) => b.value-a.value)[0];
return res.name+':'+res.value
}
solution("hello world");
this is a simple Idea that only includes one pass-through with a hashmap. The only thing this does not do is handle several max numbers. I really hope you enjoy my solution :) .
function maxChar(str) {
//Create the output and the hashmap
let m = {}, ans
//Loop through the str for each character
//Use reduce array helper because of the accumulator
str.split('').reduce((a, c) => {
//Increments Map at location c(character) unless it does not already exist
m[c] = m[c] + 1|| 1
//This checks to see if the current passthrough of m[c] is greater than or equal to the accumulator, if it is, set the answer equal to the current character. If it's not keep the ans the same.
ans = m[c] >= a ? c : ans
//Only increment the accumulator if Map at location c(character) is greater than the accumulator. Make sure to return it otherwise it won't increment.
return a = m[c] > a ? a + 1 : a
}, 1)
//Lastly return the answer
return ans
}
Simplest way to find maximum number of occurring character in string
var arr = "5255522322";
var freq:any = {};
var num;
for(let i=0;i<arr.length;i++) {
num = arr[i];
freq[num] = freq[num] >= 1 ? freq[num] + 1 : 1;
}
var sortable:any = [];
for(let i in freq)
{
sortable.push(i);
}
var max = freq[sortable[0]];
var data:any = "";
var value = sortable[0];
for(let i=0;i<sortable.length;i++) {
if(max > freq[sortable[i]]){
data = "key" + value + " " + "value" + max;
}else{
value = sortable[i]
max = freq[sortable[i]];
}
}
console.log(data);
function maxChara(string) {
charMap = {};
maxNum = 0;
maxChar = "";
string.toString().split("").forEach(item => {
if (charMap[item]) {
charMap[item]++;
} else {
charMap[item] = 1;
}
});
for (let char in charMap) {
if (charMap[char] > maxNum) {
maxNum = charMap[char];
maxChar = char;
}
}
return maxChar;
}
let result = maxChara(355385);
console.log(result);
Here str will the string that needs to be verified.
function maxCharacter(str){
let str1 = str; let reptCharsCount=0; let ele='';let maxCount=0;
let charArr = str1.split('');
for(let i=0; i< str1.length; i++){
reptCharsCount=0;
for(let j=0; j< str1.length; j++){
if(str1[i] === str1[j]) {
reptCharsCount++;
}
}
if(reptCharsCount > maxCount) {
ele = str1[i];
maxCount = reptCharsCount;
}
}
return ele;
}
input
maxCharacter('asdefdfdsdfseddssdfsdnknmwlqweeeeeeeesssssssssssseeee');
output
"s"
function freq(str) {
var freqObj = {};
str.forEach((item) => {
if (freqObj[item]) {
freqObj[item]++;
}
else {
freqObj[item] = 1;
}
});
return freqObj;
}
function findmaxstr(str) {
let max = 0,res,freqObj;
freqObj = freq(str.split(""));
for(let keys in freqObj){
if (freqObj[keys] > max) {
max = freqObj[keys];
res = keys;
}
}
console.log(res);
return res;
}
findmaxstr("javasdasdsssssscript");
const maxChar = (str) => {
let obj = {};
for (let char of str) {
(!obj[char]) ? obj[char] = 1: obj[char]++;
}
maxCharcount = Math.max(...Object.values(obj));
const key = Object.keys(obj).filter(key => obj[key] === maxCharcount);
console.log(`Most repeated character/characters in the given string "${str}" is/are given below which repeated ${maxCharcount} times`);
console.log(...key);
}
maxChar("355385");
Here is the code, where it also checks for lower and upperCase characters with the same max count and returns a Lower ASCII character as a Max.
function mostFrequent(text) {
let charObj={}
for(let char of text){
if(char!==' '){
if(charObj.hasOwnProperty(char)) charObj[char]=charObj[char]+1;
else charObj[char]= 1
}
}
let maxOccurance= Object.keys(charObj)[0], i=0;
for(let property in charObj){
if(i>0){
if(charObj[property]> charObj[maxOccurance])
maxOccurance= property
else if(charObj[property]=== charObj[maxOccurance])
{
if(property<maxOccurance)
maxOccurance=property
}
}
i++
}
return [maxOccurance, charObj[maxOccurance]]
}
let str = '355385';
let max = 0;
let char = '';
str.split('').forEach((item) => {
let current = str.split(item).length;
if (current > max) {
max = current;
char = item;
}
});
console.log(char + ' occurred ' + (max - 1) + ' times');
var exp = '35585' ;
var expCounts = { };
let maxChar = ''
let count = 0
for(let i = 0; i < exp.length; i++){
let char = exp[i]
expCounts[char] = expCounts[char] + 1 || 1
if(expCounts[char] > count){
maxChar = char
count = expCounts[char]
}
console.log(maxChar)
}
function checkNoofOccurenance(string) {
const arr = [...new Set(string.split(''))].sort();
const finalObj = {};
arr.forEach((item) => {
finalObj[item] = string.split(item).length - 1;
});
const item=Object.keys(finalObj).reduce((occ, toBeComapir)=>finalObj[occ]>finalObj[toBeComapir]?occ:toBeComapir)
return item;
}
Using Hasmaps we can find the most frequent char and occurrence all in O(N) time complexity. Below is the code. I have used one hasmap to save all the values and while i am doing it, i am also calculating the max occurrence and the max char.
var mostFreq = function(s) {
let myMap = new Map();
let temp;
let counter = 0;
let mostFrequentChar;
for(let i =0;i <s.length;i++){
if(myMap.has(s.charAt(i))){
temp = myMap.get(s.charAt(i));
temp = temp + 1;
myMap.delete(s.charAt(i));
myMap.set(s.charAt(i) , temp)
if(temp > counter){
counter = temp;
mostFrequentChar = s.charAt(i);
}
}else{
myMap.set(s.charAt(i), 1)
}
}
//if you want number of occerance of most frequent char = counter
//if you want list of each individual char and its occurrence = myMap
//if you just want the char that is most frequence = mostFrequentChar;
return mostFrequentChar;
};
If you want the count of the letter as well, You can do this
const { letter, count } = input.split("").reduce(
(acc, letter) => {
const count = input.split(letter).length - 1;
return count > acc.count
? { letter, count }
: { letter: acc.letter, count: acc.count };
},
{ letter: "", count: 0 }
);
Here We are splitting the string, applying a reduce to the result. The Reduce Counts how many instances of a character are there in a string, using input.split(letter).length - 1; And if the count is greater than the previous count, updates the accumulated value to be the current value
let string = "355385";
function printFirstRepeat(str){
let output= {};
for (let char of str) {
char = char.toLowerCase();
output[char] = ++output[char] || 1;
if(output[char] > 1) return char;
}
return "Not Found"
}
console.log(printFirstRepeat(string));
Algorithm: Find maximum occurring character in a string (time complex: O(N))
I'll provide my solution to this algo-problem by utilizing the most recent concepts of javascript
const getMaxCharacter = (str) => {
let max = 0;
let maxChar = '';
str.split('').forEach((char) => {
if (str.split(char).length > max) {
max = str.split(char).length - 1;
maxChar = char;
}
});
return `The max letter is : ${maxChar} and the max number of times it is seen is: ${max} times`;
};
Let's express an easy way of testing the function logic I wrote it:
const letter = 'Hello Student';
getMaxCharacter(letter);
In the function developed, I've used the concepts below:
Arrow Function
Anonymous Funciton
Declare property by using let/const
Template Literals
forEach(); (array helper) & split()
This is simple and optimized solution and it returns the first occurring char if there are chars equals in counts
function maxOccurance(str) {
let maxOccurringChar = "";
const charMap = {};
for (let index = 0; index < str.length; index++) {
const ele = str.charAt(index);
if (!charMap[ele]) {
charMap[ele] = {
startIndex: index,
value: 1
};
} else {
charMap[ele].value = charMap[ele].value + 1;
}
if (
!maxOccurringChar ||
charMap[maxOccurringChar].value < charMap[ele].value
) {
maxOccurringChar = ele;
} else if (
charMap[maxOccurringChar].value === charMap[ele].value &&
charMap[ele].startIndex < charMap[maxOccurringChar].startIndex
) {
maxOccurringChar = ele;
}
}
return maxOccurringChar;
}
console.log( maxOccurance("bacdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz")
);
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<p id = "myString">Hello World! I am Julio!</p>
<p id = "mRCharacter"></p>
<script>
var string = document.getElementById("myString").innerHTML;
var mRCharater = mostRepetedCharacter(string);
document.getElementById("mRCharacter").innerHTML = mRCharater;
console.log(mRCharater);
function mostRepetedCharacter(string){
var mRCharater = "";
var strLength = string.length;
var i = 0;
var count = 0;
var max = 0;
var rest = strLength - 1;
while (i < strLength){
var j = i + 1;
while (j <= rest){
if (string[i] === string[j]){
count++;
}
if (count > max){
max = count;
mRCharater = string[i];
}
j++;
}
i++;
count = 0;
}
return mRCharater;
}
</script>
</body>
</html>
enter code here