0

The answer to this has already been posted on SO, but I want to find a way that does not include complicated data structures like hashmaps. The solution needs to be from ints and football_club[0].equals(football_club[1])

String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};

//result
Sting result_club = "a value most in the array"

thank you very much.

kraskevich
  • 18,368
  • 4
  • 33
  • 45
Forbs
  • 13
  • 2

5 Answers5

0

Here is the prototype:

import java.util.Arrays;

public class WordCount
{
  public static void main(String[] args)
  {
    String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};
    // First sort the array to have the same words group togheter
    Arrays.sort(football_club);

    String result_club = "";
    String word = football_club[0];
    int count = 1, winner = 0; // word counters

    for (int i = 1 ; i < football_club.length; i++) {
      String current = football_club[i];
      if (word.equals(current)) {
        count++;
      }
      else { // word changed
        if (count > winner) { // save winner
          winner = count;
          result_club = word;
        }
        word = current; // start new word count
        count = 1;
      }
    }
    System.out.println("A value most appearing in the array " + result_club + "(" + winner +")");
  }
MaxZoom
  • 7,619
  • 5
  • 28
  • 44
0

As everyone insists, you should be using a HashMap, but for the sake of the question, let's try this (untested):

String mostFrequent = null;
int frequency = 0;
Arrays.sort(football_club);    // Use a copy if necessary

int count = 0;
for(int i = 0; i < football_club.length; i++) {
    count++;
    if(i == football_club.length - 1 || !football_club[i].equals(football_club[i + 1])) {
        if(count > frequency) {
            mostFrequent = football_club[i];
            frequency = count;
        }
        count = 0;
    }
}

mostFrequent should now contain the most frequent element.

shmosel
  • 49,289
  • 6
  • 73
  • 138
0

The comments are true with respect to Maps and efficiency, and its arguable what's simple. Anyways, you can do a few neat tricks and get your solution by falling back to string manipulation only, without the need for sorting or multiple loops e.g.

public void theMostOftenClub() {
    String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};
    String arrayToString = Arrays.toString(football_club);
    int length = arrayToString.length();
    String result_club = "";
    int count = 0;
    for (String club : football_club) {
        int clubLength = club.length();
        int clubCount =  (length - arrayToString.replace(club,"").length()) / clubLength;
        if (count < clubCount) {
            count = clubCount;
            result_club = club;
        }
    }
    System.out.println(result_club); // prints Barcelona
}

The two main lines

String arrayToString = Arrays.toString(football_club);

will give you a string equal to [Barcelona, Real Madrid, Chelsea, Real Madrid, Barcelona, Barcelona]

and

int clubCount =  (length - arrayToString.replace(club,"").length()) / clubLength;

will give you a count of each word within a script

Master Slave
  • 27,771
  • 4
  • 57
  • 55
0

You could use the Stream API, but it also comes down to using a Map, although you are not seeing it:

String result_club = Stream.of(football_club)
             .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) 
             .entrySet().stream()
             .max(Comparator.comparingLong(e -> e.getValue()))
             .map(e -> e.getKey()).orElse(null);

What it does in parts:

// group array to a map holding unique strings an its counts within the array
Map<String, Long> grouped = Stream.of(football_club)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

// find the entry of the map with the maximum count if there is one
Optional<Entry<String, Long>> max = grouped.entrySet().stream()
    .max(Comparator.comparingLong(Entry::getValue));

// geht the key of the maximum element or a default value if there is none
String result_club = max.map(Entry::getKey).orElse("Fortuna Düsseldorf");
flo
  • 9,713
  • 6
  • 25
  • 41
0

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);
}
gknicker
  • 5,509
  • 2
  • 25
  • 41