Creating a random string with only certain letters and a certain length - java

So I want to generate a random string but only want certain characters to be the string (Only ones that can be used in a file name to be hosted so something like www.example.com/HERE.EXTENTION).
So how can I make a random string that is a length that I want with only certain letters I want.
I know I can do a for look from the length, and then use the random number and cast that to a char and add it to a string. But I don't want characters that I don't want to be added and going through a loop with all that I don't want because that would take too long.

Use this quick method:
String genRand(int length){
Random rand=new Random();
String possibleLetters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.";
StringBuilder sb = new StringBuilder(length);
for(int i = 0; i < length; i++)
sb.append(possibleLetters.charAt(rand.nextInt(possibleLetters.length())));
return sb.toString();
}
Edit possibleLetters to include the characters you want. Note that \ and newlines must be escaped.

Store all your accepted letters in an array, then generate a random number between 0 and the length of this array N times, to get N indices of a letter in the array. Concatenate the letters.
EDIT:
Note that if your goal is to generate unique names, random is not the solution. A random doesn't guarantee uniqueness.

Other than the two answers -
You can have it like <yourChoiceOfName>-<currentTime>.yourext. This way the chances of two files with the same name is lesser.
The currenttime could include milliseconds.
In this case you have a known length i.e. length of yourChoiceOfName + length of currentTime + lenght of yourext.

Related

I need to format a string from an array so it is appropiate

I need to print from an array so that it has columns but even after looking around online I cannot figure this out. I have the following code:
public void printDirectory() {
System.out.println("Surname " + "Initial " + "Extension");
for (int i = 0; i < directory.length; i++) {
System.out.println(directory[i]);
}
}
public static void main(String[] args) {
ArrayDirectory r = new ArrayDirectory();
r.inputEntries();
r.printDirectory();
}
The program inputs data from a text file where there are Surnames, initials and a telephone extension. For example, I have "Smith J 0583" (There will be a number of these in the array all of different lengths) when I print them out I get very badly formatted output. I am aware that it is possible to format in Java but i am not sure how to use it since the string is all in one place.
Thank you for your help.
You can use System.out.format to do this.
Using Java formatting, you can specify the lengths of Strings. So, you can make each column a set length in characters to make it format well. The only caveat is that you need to know the maximum length surname can be. In this example, i'll just guess 12.
String formatString = "%12s %7s %9s\n";
System.out.format(formatString, "Surname", "Initial", "Extension");
System.out.format(formatString, (Object[]) directory[i].split(" "));
What the formatString does is it specifies 3 strings, one that is 12 characters in length, then 7 characters in length, then 9 characters in length, all separated by spaces. Then, it ends with a new line. When you input three strings using this, they'll always be the same lengths, as long as none go over the length, which makes for nice formatting.

How to generate a random numeric string + random char string and combine?

What I'm trying to do is to generate a random string of numbers E.G 2645237 and one char in a string in the range of A-Z E.G. W and combine the two strings to make 2645237W. I can generate a random number no problem. What I'm stuck on is: 1. Generating a random Char as a string. 2. Combining the two strings to create one string. To be clear what it's for is a school assignment to achieve some extra credit in my marking. Like always I'm not looking for the full answer. Some pseudo-code or a working example would be fine but I'd like the final "A-HA!" moment to be my own doing. A final parameter. This end result (the one string) would need to be a generated 50 times differently (I can do this) and then used as a sort of password. (Meant to replicate a PPS number, the added char is the bit that has my whole class stumped).
I'm not looking to cheat my way to a coded answer, just stuck on this problem (We've all been there)
You can generate a random character simply by doing 'a' (or 'A' for upper case) and then generating a random number from 0 to 25 and adding that to it. i.e. 'a'+3 is 'd'. Note the use of a single quote character to say this is a char literal as opposed to the double quote for a String literal.
That random character can then be appended to the string. StringBuilder would do it for you easily, I'm not sure off hand what the String + operator will do with it.
Try,
Random rn = new Random();
int range = 9999999 - 1000000 + 1;
int randomNum = rn.nextInt(range) + 1000000; // For 7 digit number
System.out.println(randomNum);
Random rc = new Random();
char c = (char)(rc.nextInt(26) + 'A');
System.out.println(c);
String str = randomNum+""+c;
System.out.println(str);
str prints like 1757217Y
To generate the letter and append on your number sequence:
String msg1 = "random number sequence";
Random gen = new Random();
char c = (char) (65 + gen.nextInt(26));
StringBuilder sb = new StringBuilder();
sb.append(msg1);
sb.append(c);
String result = sb.toString();
System.out.println(result);
By the way, 65 is the ascii code of the letter 'A' and gen.nextInt(26) generates a number between 0 and 25, ie, we have a range between 65 and 90 which are the letters' A'-'Z' in ascii table

How to detect polynomials in Java

Suppose I have a polynomial -x^2 + 2x - 1 = 0. It is read from a file.
I have the code that analyzes each character of the polynomial.
I want to create an extra step that compacts the polynomial(so the white spaces gets eliminated) so I can check if the string is in fact a polynomial which I can easily do by just checking the last 2 index of the polynomial which is the equal sign and the zero like this: (=0)
Problem is some polynomial length have different lengths which gave me the thought to use an ArrayList. Problem is I cannot declare my ArrayList to be of type Character to store each character in the sequential index of an ArrayList.
public void createEquationNoWhiteSpaces(){
// it cannot be done because there is no ArrayList of characters
textArrayList = new ArrayList<String>();
for(int i = 0; i < text.length(); i++){
// Store the characters of the polynomial in an ArrayList
// because each polynomial has different length
if(text.charAt(i) != ' ')
textArrayList = text.charAt(i);
}
}
If you want to use an array, you can certainly declare an ArrayList<Character>. However, you might want to use a StringBuilder instead of a list for this purpose anyway.
st.replaceAll("\\s","")
removes all whitespace in string st

String Manipulation in java

I have one array of strings. I want to get each of string, divide it in to 3 parts (number-string-number), and put each part in another array. At last I want to have 3 arrays which two of them store numbers and one of them stores strings. The number of spaces between numbers and strings are not fixed.
the format of the strings in the first array is:
-2.2052 dalam -2.7300
-3.0511 dan akan -0.1116
It will be great if you help me with a sample code.
Here's the algorithm you could implement :
Create your 3 output arrays. They should all have the same length as the original string array
iterate through your original array.
for each string, find the index of the first space character and the index of the last space character. (look into the javadoc of the String class for methods doing that)
extract the substring before the first space, the substring between the first and last space, and the substring after the last space. The javadoc should help you.
Convert the first and third substring into an int (see the javadoc for Double for how to do it)
store the doubles and the string into the ouput arrays.
You can use indexOf and lastIndexOf to achieve this. Try following:
String arrayWithStringAndNumber[] = new String[2];
arrayWithStringAndNumber[0] = "-2.2052 dalam -2.7300";
arrayWithStringAndNumber[1] = "-3.0511 dan akan -0.1116";
String numArray1[] = new String[2];
String numArray2[] = new String[2];
String strArray[] = new String[2];
String temp;
for (int i = 0; i < arrayWithStringAndNumber.length; i++) {
temp = arrayWithStringAndNumber[i];
numArray1[i]=temp.substring(0,temp.indexOf(" "));
numArray2[i]=temp.substring(temp.lastIndexOf(" ")+1);
strArray[i]=temp.substring(temp.indexOf(" ")+1,temp.lastIndexOf(" "));
}
Make sure all arrays are of same length.
For num arrays use type whatever you want. I think you may need double and then you can easily parse the value to fit in it.
Hope this helps.
You can use indexOf(int ch) and lastIndexOf(int ch) of String object to find the first and last whitespace character and divide the string using these two indexes. You can also trim the middle string part if needed.
So:
String[] input; // given
Double[] firstNumbers = new Double[input.length];
String[] middleParts = new String[input.length];
Double[] secondNumbers = new Double[input.length];
for(int i = 0; i < input.length; i++) {
String line = input[i];
int firstWhitespace = line.indexOf(" ");
int lastWhitespace = line.lastIndexOf(" ");
String firstNumber = line.substring(0, firstWhitespace);
String middlePart = line.substring(firstWhitespace, lastWhitespace+1);
String secondNumber = line.substring(lastWhitespace+1, line.length());
// parse numbers to double, add to an array
firstNumbers[i] = Double.parseDouble(firstNumber);
middleParts[i] = middlePart;
secondNumbers[i] = Double.parseDouble(secondNumber);
}
Usually every programming language has functions for operating on strings data. Common set of functions is
length (or len) - to get length of string
find (or indexOf or somthing like this) - to find position of character of substring
substring (or substr) - to get substring of N characters from postion P
often
left/right - to get substring of N characters from left or right string's side
Trim/leftTrim/rightTrim - to trim from left and/or right string's side all space-characters or given as function parameter character.
Always as you need to operate on strings data, try to read documentation or google. You always will find information at Internet. Good luck!

Generating random words in Java?

I wrote up a program that can sort words and determine any anagrams. I want to generate an array of random strings so that I can test my method's runtime.
public static String[] generateRandomWords(int numberOfWords){
String[] randomStrings = new String[numberOfWords];
Random random = Random();
return null;
}
(method stub)
I just want lowercase words of length 1-10. I read something about generating random numbers, then casting to char or something, but I didn't totally understand. If someone can show me how to generate random words, then I should easily be able to just use a for loop to insert the words into the array. Thanks!
Do you need actual English words, or just random strings that only contain letters a-z?
If you need actual English words, the only way to do it is to use a dictionary, and select words from it at random.
If you don't need English words, then something like this will do:
public static String[] generateRandomWords(int numberOfWords)
{
String[] randomStrings = new String[numberOfWords];
Random random = new Random();
for(int i = 0; i < numberOfWords; i++)
{
char[] word = new char[random.nextInt(8)+3]; // words of length 3 through 10. (1 and 2 letter words are boring.)
for(int j = 0; j < word.length; j++)
{
word[j] = (char)('a' + random.nextInt(26));
}
randomStrings[i] = new String(word);
}
return randomStrings;
}
RandomStringUtils from commons-lang
Why generating random words? When you can use some dictionaries.
If you want to generate random words of a given length, you'll either need an algorithm to determine if a given string is a word (hard), or access to a word list of all the words in a given language (easy). If it helps, here's a list of every word in the Scrabble dictionary.
Once you have a list of all words in a language, you can load those words into an ArrayList or other linear structure. You can then generate a random index into that list to get the random word.
You can call this method for each word you want to generate. Note that the probability of generating anagrams should be relatively low though.
String generateRandomWord(int wordLength) {
Random r = new Random(); // Intialize a Random Number Generator with SysTime as the seed
StringBuilder sb = new StringBuilder(wordLength);
for(int i = 0; i < wordLength; i++) { // For each letter in the word
char tmp = 'a' + r.nextInt('z' - 'a'); // Generate a letter between a and z
sb.append(tmp); // Add it to the String
}
return sb.toString();
}
If you want random words without using a dictionary...
Make a list of all the letters you want possible in your words
Generate a random index to pick out a letter from the list
Repeat until you have your desired word length
Repeat these steps for the number of words you want to generate.

Categories

Resources