What's wrong with my reverse() function while? - javascript

My code
When i use word cat the function doesn't return anything.
function reverse(str) {
let result = '';
let i = str.length-1;
while ( i < 0) {
result = result + str[i];
i--;
}
return result;
}// END```

You need to take length and the check for greater or equal than zero for the loop.
function reverse(str) {
let result = '';
let i = str.length - 1;
while (i >= 0) {
result = result + str[i];
i--;
}
return result;
}
console.log(reverse('cat'));
A slightly shorter approach with decrementing and check in one.
function reverse(str) {
let result = '',
i = str.length;
while (i--) result = result + str[i];
return result;
}
console.log(reverse('cat'));

Use str.length; instead of str.legth-1;
legth is not a function. The function in length
function reverse(str) {
let result = '';
let i = str.length;
while (i--) {
result = result + str[i];
}
return result;
}
console.log(reverse('ellipsis'))

You had a typo and a logic error:
function reverse(str) {
let result = '';
let i = str.length - 1; // str.length
while (i >= 0) { // greater than equal to :)
result = result + str[i];
i--;
}
return result;
}

You could use reduce
const reverse = str => str.split('').reduce((result, char) => char + result);
console.log(reverse('cat'));

Related

Function keeps timing out

This is the problem:
Complete the function splitPairs such that it splits the input string into pairs of characters. If the input string has a length that is odd, then it should replace the missing second character of the final pair with an underscore _. Note, an empty string should make your function produce an empty array.
Here is my code (it keeps timing out):
function splitPairs(input) {
let inputArray = input.split('');
let result = [];
if (inputArray.length % 2 !== 0) {
for (let i = 0; i < inputArray.length; i + 2) {
let pair = inputArray[i] + inputArray[i+1];
//push that onto the result array
result.push(pair);
}
result.push(inputArray[inputArray.length - 1] + '_');
} else {
for (let i = 0; i < inputArray.length; i + 2) {
let pair = inputArray[i] + inputArray[i+1];
result.push(pair);
}
}
return result;
}
What am I doing wrong and what is the proper way to solve this problem? It would be better if I could write the solution myself but I could use help to know what methods I should use to solve it
It's timing out because you're not incrementing i. i + 2 computes the new value but doesn't assign it anywhere. You can update i by doing i += 2 which is shorthand for i = i + 2.
You need to increment using i+=2. Also, there are some mistakes in the solution:
function splitPairs(input) {
let inputArray = input.split('');
let result = [];
if(!inputArray)
return result;
if (inputArray.length % 2 !== 0) {
for (let i = 0; i < inputArray.length-1; i+=2) {
let pair = inputArray[i] + inputArray[i+1];
result.push(pair);
}
result.push(inputArray[inputArray.length - 1] + '_');
} else {
for (let i = 0; i < inputArray.length; i += 2) {
let pair = inputArray[i] + inputArray[i+1];
result.push(pair);
}
}
return result;
}
console.log(splitPairs(""));
console.log(splitPairs("abcd"));
console.log(splitPairs("abcde"));
A simpler solution (with one loop) as mentioned in the comments would be:
function splitPairs(input) {
let inputArray = input.split('');
let result = [];
if(!inputArray)
return result;
let odd = (inputArray.length % 2 !== 0);
let len = (odd) ? inputArray.length-1 : inputArray.length;
for (let i = 0; i < len; i+=2) {
let pair = inputArray[i] + inputArray[i+1];
result.push(pair);
}
if(odd)
result.push(inputArray[inputArray.length - 1] + '_');
return result;
}
console.log(splitPairs(""));
console.log(splitPairs("abcd"));
console.log(splitPairs("abcde"));
You can use a one(two) liner
var result=str.split(/(..)/).filter(v=>v)
if (result[result.length-1].length==1) result[result.length-1]+="_"
You can do it like this
function splitPairs(input) {
return input.split('').map((c, i) => {
if (i % 2 !== 0) return;
if (input[i+1]) {
return input[i] + input[i+1];
}
return input[i] + '_';
}).filter(pair => pair);
}

NodeJS script running but logging nothing

so I am writing a function to get biggest divisor,
and I am running it in VScode using command
$ -node script.js
it is logging nothing, what am I missing?
here is the content of script.js :
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
return result;
}
if (!i) {
return result;
}
}
console.log(result);
};
LFfinder(15);
You are writing console.log() at the place where control is not reaching as per your logic. Try writing before you return the value
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
console.log(result);
return result;
}
if (!i) {
console.log(result);
return result;
}
}
};
LFfinder(15)
You don't need to return in the loop. Because of return the console.log statement is never reached. And the else part is not required. This will work:
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
break;
}
}
console.log(result);
};
LFfinder(15);
LFfinder(19);
LFfinder(200);
Note that you don't need to loop through till end. The first instance you find is the greatest, so save further iteration with break.
Also, it's better that the function returns a value instead of logging the answer.
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
break;
}
}
return result;
};
console.log(LFfinder(15));
console.log(LFfinder(19));
console.log(LFfinder(200));
its working fine, please check the link, i've tried
https://repl.it/#HarshSrivastav1/playgroundams

Given a censored string and a string of the censored vowels, return the original uncensored string

<script>
var immutable = "";
var count = 0;
function uncensor(str1, str2) {
for (var i = 0; i < str.length; i++) {
if (str1[i] == "*") {
immutable =
str1.slice(0, i) +
str2[count] +
str1.slice(i + 1, str1.length - 1);
count++;
}
}
return immutable;
}
document.write(uncensor("Wh*r* d*d my v*w*ls g*?", "eeioeo"));
// uncensor("Wh*r* d*d my v*w*ls g*?", "eeioeo")
</script>
My logic is updating the variable immutable every time there is a "*". So by the end of the loop all the "*" will be replaced by the characters in str2 one by one.
I expect the result to be "Where did my vowels go?"
The output is none.
You can try to iterate through input and capture result in an array:
var immutable = "";
var count = 0;
function uncensor(str1, str2) {
let result = [];
for (var i = 0; i < str1.length; i++) {
if (str1[i] == "*") {
result.push(str2[count++]);
} else {
result.push(str1[i]);
}
}
return result.join("");
}
console.log(uncensor("Wh*r* d*d my v*w*ls g*?", "eeioeo"));
EDIT: the fact that string is immutable means that every time you use splice or + character you create a new string. If you want to use your approach with splice you need to concatenate parts of str with characters from str2 like below however the upper solution should be a way more performant:
var result = "";
var count = 0;
var lastCensored = 0;
function uncensor(str1, str2) {
for (var i = 0; i < str1.length; i++) {
if (str1[i] == "*") {
result +=
str1.slice(lastCensored, i) +
str2[count++];
lastCensored = i + 1;
}
}
return result + str1.slice(lastCensored, str1.length);
}
document.write(uncensor("Wh*r* d*d my v*w*ls g*?", "eeioeo"));
// uncensor("Wh*r* d*d my v*w*ls g*?", "eeioeo")
You could also use .replace:
function uncensor(str, v) {
return str.replace(/\*/g, () => ([, ...v] = v)[0]);
}

Write a function that returns a subset of a string between one index and another without using built-in function

Write a function that returns a subset of a string between one index and another. Without using any built-in function: substr, substring, slice, splice...
Hi guys, can you help me with this, the code went wrong and i don't know how to fix it.Thanks
Example (("abcd",1,10) return "bcd")
I alter it thanks to you guys. But it still missing something, like it only work if the substring is the start of the string.
function func3(str, indexStart, indexEnd) {
var result = "";
for (var i = indexStart; i < indexEnd && i < str.length; i++) {
var x = str.charAt(i);
if (indexEnd > i > indexStart) {
var y = str.charAt(i);
}
}
result += x + y
}
return result
}
console.log(func3('abcdxyz', 1, 10));
You could check if i is not only smaller than the given end, but also if the length is smaller than the length of the string.
function func3(str, indexStart, indexEnd) {
var result = "";
for (var i = indexStart; i < indexEnd && i < str.length; i++) {
result += str[i];
}
return result;
}
console.log(func3("abcd", 1, 10));
An even shorter approach by taking the minimum length in advance.
function func3(str, indexStart, indexEnd) {
var result = "",
i,
l = Math.min(indexEnd, str.length);
for (i = indexStart; i < l; i++) {
result += str[i];
}
return result;
}
console.log(func3("abcd", 1, 10));
var result = "";
for (var i=indexStart; i < indexEnd; i++){
result += str.charAt(i);
}
return result
function func3(str, indexStart, indexEnd) {
var result="";
for (var i=Math.max(0, indexStart); i<=indexEnd || i>str.lengths; i++) {
result += str.charAt(i);
}
return result;
}
console.log(func3("abcd", 1, 10));
console.log(func3("abcd", -1, 10));
console.log(func3("abcd", 2, 2));
console.log(func3("abcd", 7, 10));
If prototype functions ain't your thing, this may be what you are looking for:
function charBetween(str, start, end) {
let res = '';
if (start > end) return res;
while (str[start] !== undefined && start <= end) {
res += str[start];
start++;
}
return res;
}
console.log(charBetween("This is a test.", 9, 100));
I have also added a prototype function to String's if you would like to use it. By doing this you may call this function like so:
String.prototype.charBetween = function(start, end) {
'use strict'; // `this` refers to an object without strict set.
let res = '';
if (start > end) return res;
while (this[start] !== undefined && start <= end) {
res += this[start];
start++;
}
return res;
}
console.log("This is a test.".charBetween(9, 100));
Hope this helps,
You are declaring two variables x and y and y may not be present every time.
function func3(str,indexStart,indexEnd){
var result = "";
var x;
for (var i=indexStart; i < indexEnd; i++){
x = str.charAt(i);
if (indexEnd>i && i > indexStart){
x =str.charAt(i);
}
else if (i>indexEnd){
break;
}
result += x
}
return result
}
console.log(func3("abcd",1,3))
A simpler way is to get the the min value out of length of string an end index. And then loop only upto that.
function func3(str,indexStart,indexEnd){
var result = "";
let len = Math.min(str.length,indexEnd)
for (var i=indexStart; i < len; i++){
result += str[i];
}
return result
}
console.log(func3("abcd",1,10))

Finding the most frequent character in a string javascript

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

Categories

Resources