I am making a Java type teacher(to teach typing). I need to generate random words that will be given to type. I made a program to generate random words but it generates just random words without any meaning, but I want to generate real words.
What would be the best way to achieve this?
import java.util.Random;
public class Generator {
private String CHAR_LIST = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private int No_Of_Chars = 2;
public Generator(String CHARS, int No_Of_Char) {
No_Of_Chars = No_Of_Char;
CHAR_LIST = CHARS;
}
public String RandomString() {
String randStr = "";
for (int i = 0; i < No_Of_Chars; i++) {
int number = getRandomNumber();
char ch = CHAR_LIST.charAt(number);
randStr = randStr + ch;
}
return randStr;
}
private int getRandomNumber() {
int randomInt = 0;
Random randomGenerator = new Random();
randomInt = randomGenerator.nextInt(CHAR_LIST.length());
if (randomInt - 1 == -1) {
return randomInt;
} else {
return randomInt - 1;
}
}
}
As other said get a dictionary.
Ask your browser for a word list site. I found this one at the first search : http://www.md5this.com/tools/wordlists.html
Load the file in an ArrayList, a word by element.
Get a random index by int idx = new Random().nextInt(yourArray.size());.
Return the word at that index and remove it String chosenWord = yourArray.remove(idx);
Create a list of words in some text file
Load that text file into your program
Shuffle that list
Use each one in order
(3) is the only step that needs thought: use java.util.Collections#shuffle
Your best option here would be to create a list of words. Next you will randomly pick words from this list for your students to type.
Related
New to arrays here... I want to get a random integer and set that integer to each individual letter in the alphabet like integer 1 = a. So that I can print a random letter in the alphabet without using a pre-existing java method for random string. I don't want to generate a random string this is the way I need it.
{
public static void main(String[] args)
{
Random Gen = new Random();
String[] letters = new String[50];
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int randomInt = Gene.nextInt(26);
String second = "" + randomInt;
System.out.println(second);
//Not sure what next....
}
}
System.out.println(alphabet.charAt(randomInt)) will print the character at (zero-based) position randomInt in your alphabet string.
(Note that randomInt == 0 will output a, 1 outputs b and so on.)
Adapt this to your need.
There is an alternative way of selecting a random character, this is in my opinion a more elegant solution if all you will ever need is lowercase characters. It more explicitly conveys that the generated character will be a random lowercase latin letter, because it does not use an alphabet string constant.
public static void main(final String args[]) {
final Random random = new Random();
final String[] array = new String[50];
for (int i = 0; i < array.length; i++) {
array[i] = String.valueOf(generateRandomLetter(random));
}
System.out.println(Arrays.toString(array));
}
private static char generateRandomLetter(Random random) {
return (char) ('a' + random.nextInt(26));
}
alphabet.charAt(randomInt) would provide you the required random character from alphabet string.
What is the most simple way? Minimizing any imports.
This one is good:
String str = Long.toHexString(Double.doubleToLongBits(Math.random()));
But it's not perfect, for example it complicates with custom length.
Also an option: How to make this String unique?
Create a String of the characters which can be included in the string:
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Generate an integer using the Random class and use it to get a random character from the String.
Random random = new Random();
alphabet.charAt(random.nextInt(alphabet.length()));
Do this n times, where n is your custom length, and append the character to a String.
StringBuilder builder = new StringBuilder(n);
for (int i = 0; i < n; i++) {
builder.append(/* The generated character */);
}
Together, this could look like:
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public String generateString(int length) {
Random random = new Random();
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
builder.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
}
return builder.toString();
}
RandomStringUtils from commons-lang. If you don't wish to import, check out its source.
Hi biologist here with a little bit of coding background. my goal is to be able to input a string of characters and the code to be able to tell me how many times they occur and at what location in the string.
so ill be entering a string and i want the location and abundance of sq and tq within the string. with the location being the first character e.g njnsqjjfl sq would be located at postition 4.
This is what ive come up with so far (probably very wrong)
string S = "...";
int counter =0;
for(int i=0; i<s.length; i++){
if(s.charAt (i) == 'sq')}
counter++;})
string S = "...";
int counter =0;
for(int i=0; i<s.length; i++){
if(s.charAt (i) == 'tq')}
counter++;})
any input will help, thankyou
So , you can have multiple occurrences of "sq" and "tq" in your code, so you can have 2 arraylists to save these two separately(or one to save them together).
ArrayList<Integer>sqLocation = new ArrayList<>();
ArrayList<Integer>tqLocation = new ArrayList<>();
for(int i =0;i<s.length()-1;i++){
if(s.charAt(i)=='s' && s.charAt(i+1)=='q'){
sqLocation.add(i);
}
else if(s.charAt(i)=='t' && s.charAt(i+1)=='q'){
tqLocation.add(i);
}
}
System.out.println("No. of times sq occurs = "+sqLocation.size());
System.out.println("Locations ="+sqLocation);
System.out.println("No. of times tq occurs = "+tqLocation.size());
System.out.println("Locations ="+tqLocation);
This can be achieved using regex. Your use case is to count occurrences and position of those occurrences. The method match returns an integer list which is position and count is size of list
Exmaple code
public class RegexTest {
public static List<Integer> match(String text, String regex) {
List<Integer> matchedPos = new ArrayList<>();
Matcher m = Pattern.compile("(?=(" + regex + "))").matcher(text);
while(m.find()) {
matchedPos.add(m.start());
}
return matchedPos;
}
public static void main(String[] args) {
System.out.println(match("sadfsagsqltrtwrttqsqsqsqsqsqs", "sq"));
System.out.println(match("sadfsagsqltrtwrttqksdfngjfngjntqtqtqtqtqtq", "tq"));
}
}
what you want is a HashMap <String, List <Integer>>
this will hold, the String that you are looking for e.g. sq or tq, and a List of the positions that they are at.
You want to loop around using String.indexOf see https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)
psuedocode being
String contents = "sadfsagsqltrtwrttqksdfngjfngjntqtqtqtqtqtq";
map.add (lookFor, new ArrayList ());
int index = 0;
while ((index = contents.indexOf (lookFor, index)) != -1) {
list = map.get (lookFor);
list.add (index);
}
You should use not charAt but substring to get a part of String.
int count(String s, String target) {
int counter = 0;
int tlen = target.length();
for (int i = tlen; i < s.length(); i++) {
if (s.substring(i - tlen, i).equals(target)) {
counter++;
}
}
return counter;
}
// in some method
count("...", "sq");
count("...", "tq");
I have written this java method but sometimes the color String is only 5 characters long. Does anyone know why?
#Test
public void getRandomColorTest() {
for (int i = 0; i < 20; i++) {
final String s = getRandomColor();
System.out.println("-> " + s);
}
}
public String getRandomColor() {
final Random random = new Random();
final String[] letters = "0123456789ABCDEF".split("");
String color = "#";
for (int i = 0; i < 6; i++) {
color += letters[Math.round(random.nextFloat() * 15)];
}
return color;
}
Working with floats and using round is not a safe way of creating such random colors.
Actually a color code is an integer in hexadecimal formatting. You can easily create such numbers like this:
import java.util.Random;
public class R {
public static void main(String[] args) {
// create random object - reuse this as often as possible
Random random = new Random();
// create a big random number - maximum is ffffff (hex) = 16777215 (dez)
int nextInt = random.nextInt(0xffffff + 1);
// format it as hexadecimal string (with hashtag and leading zeros)
String colorCode = String.format("#%06x", nextInt);
// print it
System.out.println(colorCode);
}
}
DEMO
Your split will generate an array of length 17 with an empty string at the beginning. Your generator occasionally draws that zeroth element which will not contribute to the length of the final string. (As a side effect, F will never be drawn.)
Accept that split has that odd behaviour and work with it: Ditch that nasty formula that uses round. Use 1 + random.nextInt(16) instead as your index.
Don't recreate the generator on each call of getRandomColor: that ruins the generator's statistical properties. Pass random as a parameter to getRandomColor.
Also to ensure that your String always contains 6 characters, try to replace the for loop with a while. Please see:
while (color.length() <= 6){
color += letters[random.nextInt(17)];
}
I need a String array with the following attributes:
4 digits numbers
No repeating digits ("1214" is invalid)
No 0's
Is there an easier way to do this than manually type it? Like:
String[] s = {"1234","1235",1236",1237",1238",1239","1243","1245"};
Sorry for my English!
The following code will generate an array with your specifications.
public class Test {
public static void main(String[] args) {
List<String> result = new ArrayList<>();
Set<Character> set = new HashSet<>();
for (int i = 1234; i <= 9876; i++) {
set.clear();
String iAsString = Integer.toString(i);
char[] chars = iAsString.toCharArray();
boolean valid = true;
for (char c : chars) {
if (c == '0' || !set.add(c)) {
valid = false;
break;
}
}
if (valid) {
result.add(iAsString);
}
}
String[] yourStringArray = result.toArray(new String[result.size()]);
System.out.println(Arrays.toString(yourStringArray));
}
}
****edit****
Just saw that it is in Java. So use this function: String.valueOf(number) to convert integer to string if none of the digits are repeats in the loop.
Not sure what language you are doing but I am assuming no repeats not replies.
So what you can do is have a loop from 0 to 9999 and then run through all the numbers while checking if each digit has repeats if so discard number (do not store it into array).
You can convert integers to strings in many languages in their function so you can do that then store it into array.
Good luck.
Hope this helped (fastest solution from my head...there could be more efficient ones)
Try this method for creating Random number with your structure :
ArrayList<Integer> rawNumbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
public String createRandomNumberSring()
{
String result = "";
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(rawNumbers);
for(int i = 0; i < 4; i++)
{
int index = (int)(Math.random() * (numbers.size() + 1));
result += numbers.get(index).toString();
numbers.remove(index);
}
return result;
}