Skip to content

Instantly share code, notes, and snippets.

@Phoenix-Effect
Created July 3, 2018 08:07
Show Gist options
  • Save Phoenix-Effect/685f3ae0c4ebfc307c0f63df6afc9e73 to your computer and use it in GitHub Desktop.
Save Phoenix-Effect/685f3ae0c4ebfc307c0f63df6afc9e73 to your computer and use it in GitHub Desktop.
Count frequency of a string in a given array without using any functions or classes in Java.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
static void staircase(String[] votes) {
ArrayList<String> arrayList = new ArrayList<>();
for(int i = 0; i < votes.length; i++){
arrayList.add(votes[i]);
}
Collections.sort(arrayList);
String[] sortedArray = arrayList.toArray(new String[arrayList.size()]);
int voteCount = 1, winnerCount = 0;
String lastName = "";
String winnerName = sortedArray[sortedArray.length - 1];
for(int i = 0; i < sortedArray.length; i++){
if(sortedArray[i] == lastName) {
voteCount++;
if(voteCount >= winnerCount){
winnerName = lastName;
winnerCount = voteCount;
}
} else {
voteCount = 1;
lastName = sortedArray[i];
}
}
System.out.println(winnerName);
String s = Arrays.toString(arrayList.toArray());
System.out.println(s);
}
public static void main(String[] args) {
String[] array = {"Alex", "Michael", "Harry", "Dave", "Michael", "Victor", "Harry", "Alex", "Mary", "Mary"};
staircase(array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment