Created
June 10, 2018 03:12
-
-
Save safaorhan/8965e0c2a1d3751a36ed103b5935a479 to your computer and use it in GitHub Desktop.
Random english letter generator according to their frequencies in English.
This file contains 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
package com.safaorhan.example; | |
public class FrequentLetterGenerator { | |
private static char[] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); | |
private static float[] weights = new float[]{ | |
8.167f, | |
1.492f, | |
2.782f, | |
4.253f, | |
12.702f, | |
2.228f, | |
2.015f, | |
6.094f, | |
6.966f, | |
0.153f, | |
0.772f, | |
4.025f, | |
2.406f, | |
6.749f, | |
7.507f, | |
1.929f, | |
0.095f, | |
5.987f, | |
6.327f, | |
9.056f, | |
2.758f, | |
0.978f, | |
2.361f, | |
0.150f, | |
1.974f, | |
0.074f}; | |
public static char generate() { | |
float totalWeight = 0f; | |
for (int i = 0; i < letters.length; i++) { | |
totalWeight += weights[i]; | |
} | |
int randomIndex = -1; | |
float random = (float) (Math.random() * totalWeight); | |
for (int i = 0; i < letters.length; i++) { | |
random -= weights[i]; | |
if (random <= 0.0d) { | |
randomIndex = i; | |
break; | |
} | |
} | |
return letters[randomIndex]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment