Find Most Common String in an Array

Find the most common substring in an array of strings with a given sequence length

here is a solution using a for loop and recursive call

const getSequence = (list, length, check) => {
if(!list.length || (check && check.length < length)) {
return false;
}
let result = check || list[0]; //setting first item as a result
let found = true;

let i;
for(i = 1; i<list.length; i++) {
if(list[i].indexOf(result.substring(0, length)) == -1) {
found = false;
break;
}
}
if(!found) {
let val = getSequence(list, length, result.substring(1, result.length)) //calling same function by removing first char
if(val) {
return val;
}
}
else {
return result.substring(0, length);
}
}

console.log(getSequence(["abc", "usbcj", "bcdeh"], 2))
console.log(getSequence(["terrific", "specific"], 4))
console.log(getSequence(["test", "text"], 2))

C# Find most common strings in string array

This could be done as follows -

 var nameGroup = names.GroupBy(x => x);
var maxCount = nameGroup.Max(g => g.Count());
var mostCommons = nameGroup.Where(x => x.Count() == maxCount).Select(x => x.Key).ToArray();

Find most common string in an array

Ruby < 2.2

#!/usr/bin/ruby1.8

def most_common_value(a)
a.group_by do |e|
e
end.values.max_by(&:size).first
end

x = ["1.111", "1.122", "1.250", "1.111"]
p most_common_value(x) # => "1.111"

Note: Enumberable.max_by is new with Ruby 1.9, but it has been backported to 1.8.7

Ruby >= 2.2

Ruby 2.2 introduces the Object#itself method, with which we can make the code more concise:

def most_common_value(a)
a.group_by(&:itself).values.max_by(&:size).first
end

As a monkey patch

Or as Enumerable#mode:

Enumerable.class_eval do
def mode
group_by do |e|
e
end.values.max_by(&:size).first
end
end

["1.111", "1.122", "1.250", "1.111"].mode
# => "1.111"

Find the most common element in a string array GO

winner is always 0 and you never update it. then after incrementing your direction variables (N, O, Z and W), you immediately overwrite them with the zero value stored in winner. You need to reverse the order of the assignment.

Like in this change: https://go.dev/play/p/VaJgZcijFdh

Note also, that capitalized variables in Go mean they're exported

Getting the most frequent value from an string array

Here's a solution using zero features from java.util package, just raw arrays and looping.

public static void main(String[] args)
{
String[] football_club = { "Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona" };
boolean[] seen = new boolean[football_club.length];
String result_club = null;
int result_count = 0;
for (int i = 0; i < football_club.length; i++) {
if (!seen[i]) {
seen[i] = true;
int count = 1;
for (int j = i + 1; j < football_club.length; j++) {
if (!seen[j]) {
if (football_club[i].equals(football_club[j])) {
seen[j] = true;
count++;
}
}
}
if (count > result_count) {
result_count = count;
result_club = football_club[i];
}
}
}
System.out.println(result_club);
}

Find most common string in a 2D list

  1. Flatten the list with itertools.chain.from_iterable
  2. Apply a Counter.

Demo:

>>> from itertools import chain
>>> from collections import Counter
>>>
>>> lst = [['Mohit', 'shini','Manoj','Mot'],
...: ['Mohit', 'shini','Manoj'],
...: ['Mohit', 'Vis', 'Nusrath']]
...:
>>> Counter(chain.from_iterable(lst)).most_common(1)[0][0]
'Mohit'

Details:

>>> list(chain.from_iterable(lst))
['Mohit',
'shini',
'Manoj',
'Mot',
'Mohit',
'shini',
'Manoj',
'Mohit',
'Vis',
'Nusrath']
>>> Counter(chain.from_iterable(lst))
Counter({'Manoj': 2, 'Mohit': 3, 'Mot': 1, 'Nusrath': 1, 'Vis': 1, 'shini': 2})
>>> Counter(chain.from_iterable(lst)).most_common(1)
[('Mohit', 3)]

Some timings:

>>> lst = lst*100
>>> %timeit Counter(chain.from_iterable(lst)).most_common(1)[0][0] # timgeb
53.7 µs ± 411 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit max([x for i in lst for x in i], key=l.count) # U9-Forward
207 µs ± 389 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit Counter([x for sublist in lst for x in sublist]).most_common(1)[0][0] # Curious_Mind/Kevin Fang #1
75.2 µs ± 2.6 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit Counter(item for sublist in lst for item in sublist).most_common(1)[0][0] # Kevin Fang #2
95.2 µs ± 2.07 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit flat = list(chain.from_iterable(lst)); max(set(flat), key=flat.count) # Mayank Porwal
98.4 µs ± 178 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

(Note that Kevin Fang's second solution is a bit slower than the first one, but more memory efficient.)

Java: how to find top 10 most common String + frequency in ArrayList?

You could do it in two steps, using Java 8 streams:

Map<String, Long> map = list.stream()
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));

List<Map.Entry<String, Long>> result = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.limit(10)
.collect(Collectors.toList());

The first stream maps words to their frequency by using Collectors.groupingBy() along with Collectors.counting().

This returns a map, whose entries are streamed and sorted by map entry value, in reverse order. Then, the stream is limited to keep only 10 elements, which are finally collected to a list.

Get the most common (frequent) string entry in array

You can use GroupBy:

var mostCommonValue = values.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.FirstOrDefault();


Related Topics



Leave a reply



Submit