How to Find Word with The Greatest Number of Repeated Letters

Return the first word with the greatest number of repeated letters

I think the problem is that you're placing the return statement inside your outermost loop. It should be inside your inner loop.

So you have to place the return statement within the inner loop.

Correct use of return

     if (countNew > count) {
count = countNew;
word = arr[i];
}
return word;
}
}
}

finding the word with most repeated letters from a string containing a sentence in python

You are resetting the most_repeat_count variable for each word to 0. You should move that upper in you code, above first for loop, like this:

def most_repeating_word(strg):
words =strg.split()
max_repeat_count = 0
for words1 in words:
dict1 = {}
for letter in words1:
if letter not in dict1:
dict1[letter] = 1
else:
dict1[letter] += 1
if dict1[letter]> max_repeat_count:
max_repeat_count = dict1[letter]
most_repeated_char = letter
result=words1
return result

Hope this helps

How to find word with the greatest number of repeated letters

I'd do as below :

s = "aabcc ddeeteefef iijjfff" 
# intermediate calculation that's happening in the final code
s.split(" ").map { |w| w.chars.max_by { |e| w.count(e) } }
# => ["a", "e", "f"] # getting the max count character from each word
s.split(" ").map { |w| w.count(w.chars.max_by { |e| w.count(e) }) }
# => [2, 5, 3] # getting the max count character's count from each word
# final code
s.split(" ").max_by { |w| w.count(w.chars.max_by { |e| w.count(e) }) }
# => "ddeeteefef"

update

each_with_object gives better result than group_by method.

require 'benchmark'

s = "aabcc ddeeteefef iijjfff"

def phrogz(s)
s.scan(/\w+/).max_by{ |word| word.chars.group_by(&:to_s).values.map(&:size).max }
end

def arup_v1(s)
max_string = s.split.max_by do |w|
h = w.chars.each_with_object(Hash.new(0)) do |e,hsh|
hsh[e] += 1
end
h.values.max
end
end

def arup_v2(s)
s.split.max_by { |w| w.count(w.chars.max_by { |e| w.count(e) }) }
end

n = 100_000
Benchmark.bm do |x|
x.report("Phrogz:") { n.times {|i| phrogz s } }
x.report("arup_v2:"){ n.times {|i| arup_v2 s } }
x.report("arup_v1:"){ n.times {|i| arup_v1 s } }
end

output

            user     system      total        real
Phrogz: 1.981000 0.000000 1.981000 ( 1.979198)
arup_v2: 0.874000 0.000000 0.874000 ( 0.878088)
arup_v1: 1.684000 0.000000 1.684000 ( 1.685168)

Find the word with the greatest numbers of repeated letters

You almost did it and I suppose you're looking into something like this:

static int mostFreqCharCount(final String word) {
final int chars[] = new int[256];

int max = 0;
for (final char c : word.toCharArray()) {
chars[c]++;
if (chars[c] > chars[max]) // find most repetitive symbol in word
max = c;
}
return chars[max];
}

public static void main(final String[] args) {
System.out.println("Enter any sentence or word combination: ");

final Scanner kbd = new Scanner(System.in);
final String myString = kbd.nextLine();
kbd.close();

int maxC = 0;
String result = "";

final String[] words = myString.split("\\s+");
for (final String word : words) {
final int c = mostFreqCharCount(word);
if (c > maxC) {
maxC = c;
result = word;
}
}

if (maxC > 1) // any word has at least 1 symbol, so we should return only 2+
System.out.println(result);
}

the main idea - calculate number of most frequent symbol for each word and store only maximal one in variables maxC and result

Find the greatest number of repeated letter in a word in Javascript

Here is the javascript way of accomplishing this. Doing this with regular expressions is not possible.

var exp = 'hello world' ;
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.log(maxKey + ":" + expCounts[maxKey]); //logs l:3

JSFiddle

https://jsfiddle.net/v72qa872/

Letter Count - How to return the first word with the highest amount of repeating letters?

Start with the simpler problem of getting the frequency of each letter in a word...

// given "sassy", will return { s:3, a:1, y:1 }
function letterFrequency(word) {
return word.split('').reduce((acc, letter) => {
if (!acc[letter]) acc[letter] = 0;
acc[letter]++;
return acc;
}, {});
}

A simple problem to get the max frequency...

// given { s:3, a:1, y:1 }, will return 3
function maxLetterFrequency(word) {
return Math.max(...Object.values(letterFrequency(word)));
}

Another simple problem to sort a sentence by frequency...

// given "She sells seashells by the seashore"
// returns ["seashells", "sells", "seashore", "She", "by", "the"]
function wordsOrderedByMaxLetterFrequency(sentence) {
let words = sentence.split(' ');
words.sort((a, b) => {
return maxLetterFrequency(b) - maxLetterFrequency(a);
});
return words;
}

The first word in the resulting array is the answer. You can retest max frequencies in that word to determine of the answer should be -1.

Demo...

// given "sassy", will return { s:3, a:1, y:1 }
function letterFrequency(word) {
return word.split('').reduce((acc, letter) => {
if (!acc[letter]) acc[letter] = 0;
acc[letter]++;
return acc;
}, {});
}

// given { s:3, a:1, y:1 }, will return 3
function maxLetterFrequency(word) {
return Math.max(...Object.values(letterFrequency(word)));
}

// given "She sells seashells by the seashore"
// returns ["seashells", "sells", "seashore", "She", "by", "the"]
function wordsOrderedByMaxLetterFrequency(sentence) {
let words = sentence.split(' ');
words.sort((a, b) => {
return maxLetterFrequency(b) - maxLetterFrequency(a);
});
return words;
}

const sentence = "She sells seashells by the seashore";
const sorted = wordsOrderedByMaxLetterFrequency(sentence);
console.log(sorted);
console.log('best word:', sorted[0]);
console.log('max freq in best word:', maxLetterFrequency(sorted[0]));

Is there an easy way to get the number of repeating character in a word?

Original question: order of repetition does not matter

You can subtract the number of unique letters by the number of total letters. set applied to a string will return a unique collection of letters.

x = "loooooveee"
res = len(x) - len(set(x)) # 6

Or you can use collections.Counter, subtract 1 from each value, then sum:

from collections import Counter

c = Counter("loooooveee")

res = sum(i-1 for i in c.values()) # 6

New question: repetitions must be sequential

You can use itertools.groupby to group sequential identical characters:

from itertools import groupby

g = groupby("aooooaooaoo")
res = sum(sum(1 for _ in j) - 1 for i, j in g) # 5

To avoid the nested sum calls, you can use itertools.islice:

from itertools import groupby, islice

g = groupby("aooooaooaoo")
res = sum(1 for _, j in g for _ in islice(j, 1, None)) # 5

Return most repeated letter in a string of words using nested for loops in javascript

I will not produce new code from scratch, but take your code and show where the issues are:

1. Why your code returns all words

Look at this code, where I hide some parts:

  for (var i = 0; i < wordArray.length; i++) {
var count = 0;
// two nested loops open and close here //
// ...
if (countNew > count) {
count = countNew;
results.push(wordArray[i]);
// ...
}
}

This code shows that in each iteration you reset count to zero, so the if at the end will always be true. As a consequence you get all words in your result.

2. Counter too high

When you increase countNew you keep increasing it even when you are already checking the next character, so in the end it will total the number of all letter repetitions in the word you are looking at, without distinction.

3. Levels of counting

You currently use 2 count variables, but you actually need 3:

  • count: for the maximum number of repetition found in any word
  • countThisWordsBestLetter: the highest repetition found in the current word
  • countLetter: the repetition count for the current letter in the current word

4. Corrected code

function repeatedLetterCounter(str) {    str = str.toLowerCase();    var wordArray = str.split(" ");
var results = []; var count = 0; for (var i = 0; i < wordArray.length; i++) { var word = wordArray[i]; var countThisWordsBestLetter = 0; for (var a = 0; a < word.length; a++) { var countLetter = 0; var letter = word[a]; for (var b = a + 1; b < word.length; b++) { var nextLetter = word[b]; if (letter === nextLetter) { countLetter += 1; } } if (countLetter > countThisWordsBestLetter) { countThisWordsBestLetter = countLetter; } } if (countThisWordsBestLetter > count) { // forget any words we gathered before: results = []; } if (countThisWordsBestLetter >= count) { count = countThisWordsBestLetter; results.push(wordArray[i]); } } return results;}console.log(repeatedLetterCounter("No, Bob ran across the Mississippi."));// for this snippet only:document.write( JSON.stringify(repeatedLetterCounter("No, Bob ran across the Mississippi.")));

How to find words in a string that have consecutive letters in R language

You can use

new <- unlist(str_extract_all(text, "\\p{L}*(\\p{L})\\1+\\p{L}*"))
i <- max(nchar( unlist(str_extract_all(new, "(.)\\1+")) ))

With str_extract_all(text, "\\p{L}*(\\p{L})\\1+\\p{L}*") you will extract all words containing at least two consecutive identical letters, and with max(nchar( unlist(str_extract_all(new, "(.)\\1+")) )) you will get the longest repeated letter chunk.

See the R demo online:

library(stringr)
text <- 'tessst gfvdsvs bbbddsa daxz'
new <- unlist(str_extract_all(text, "\\p{L}*(\\p{L})\\1+\\p{L}*"))
# => [1] "tessst" "bbbddsa"
i <- max(nchar( unlist(str_extract_all(new, "(.)\\1+")) ))
# => [1] 3

See this regex demo. Regex details:

  • \p{L}* - zero or more letters
  • (\p{L}) - a letter captured into Group 1
  • \1+ - one or more repetitions of the captured letter
  • \p{L}* - zero or more letters

String with the highest frequency of recurring letters in a word

The problem with your code is the positioning of the following section of code:

if(count !== 1){
return finalword;
}

Move it from where it currently is to just before the return -1, like so:

for(var words in wordsAndLetters){
wordsAndLetters[words] = countWordLetters(words);
var highestLetterFrequency = wordsAndLetters[words];
for(var values in highestLetterFrequency){
if(highestLetterFrequency[values] > count){
count = highestLetterFrequency[values];
finalword = words;
}
}
}
if(count !== 1){
return finalword;
}
return -1;

The problem with your original code is that your were returning the first word that had repeating characters, which meant your code didn't get far enough to check if any subsequent words had more repeating characters.

Also, just for fun, here is my alternative solution.



Related Topics



Leave a reply



Submit