Last active
June 17, 2024 20:53
-
-
Save nickbauman/6b78cf75b65a0a57699ec690c9ba006c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Random; | |
import java.util.Arrays; | |
import java.util.TreeSet; | |
/* | |
Report the frequency of 100k random selections of strings in an array | |
*/ | |
public class ArrayOfStrings { | |
static String[] wordCorpusStrings = { "Achilles", "Hector", "Zeus", "Homer", "Iliad", "Troy", "Odysseus", "Agamemnon", | |
"War","Hero", "Clytymestra", "Priam", "Aeneas", "Paris", "Helen", "Aphrodite", "Apollo", "Athena", "Hera", "Breisis",}; | |
@FunctionalInterface | |
interface A { | |
String[] randomStrings(int numberOfStrings, List<String> randomStrings, Random random); | |
} | |
public static void main(String[] args) { | |
A obj = (int numberOfStrings, List<String> randomStrings, Random random) -> { | |
for (int i = 0; i < numberOfStrings; i++) { | |
randomStrings.add(wordCorpusStrings[random.nextInt(wordCorpusStrings.length)]); | |
} | |
return randomStrings.toArray(new String[0]); | |
}; | |
String[] strings = obj.randomStrings(100000, new ArrayList<>(), new Random()); | |
Arrays.sort(strings); | |
TreeSet<String> set = new TreeSet<>(); | |
set.addAll(Arrays.asList(strings)); | |
System.out.println("all Strings\n"); | |
for (String string : strings) { | |
System.out.println(string); | |
} | |
System.out.println("\nUnique Strings\n"); | |
for (String string : set) { | |
System.out.println(string); | |
} | |
System.out.println("\nFrequencies\n"); | |
for (String string : set) { | |
int start = Arrays.asList(strings).indexOf(string); | |
int frequency = 0; | |
for (int i = start; i < strings.length; i++) { | |
if (strings[i].equals(string)) { | |
frequency++; | |
} else { | |
break; | |
} | |
} | |
String s = String.format("%s : %d", string, frequency); | |
System.out.println(s); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment