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
Related
I have to convert a binary number to a hex number. The way I have decided to do this is to split the binary string into several strings of length 4 and assign each string its corresponding value in hex number (i.e. 1000 = 8, 1101 = D).
I have seen several question asking for a way to split a string into strings of size 4 the same thing but all of those solutions used a regex that gave a single string. For example I found this line of code in a solution:
System.out.println(Arrays.toString("String".split("(?<=\G.{4})")));
When I tried to use it with the binary number "10011000", I got "[1001, 1000]" but as a single string (the brackets, comma, and blank space were included as characters) and I was left with the same problem, how do I split a string.
Is there a way to split a string into an array of smaller strings?
You can try making the string a char array and then into another array of strings, add each 4 characters of the char array.
Try this:
String BinaryNumber = "10011010";
char[] n = new char[BinaryNumber.length()];
for(int i=0; i<BinaryNumber.length(); i++){
n[i] = BinaryNumber.charAt(i);
}
String str;
String[] NumberArray = new String[(BinaryNumber.length())/4];
int count = 0;
for(int i=0; i<BinaryNumber.length(); i+=4){
str = String.valueOf(n[i])+String.valueOf(n[i+1])+String.valueOf(n[i+2])+String.valueOf(n[i+3]);
NumberArray[count] = str;
count++;
}
I think this might be the solution, though it will only work if the length of the BinaryNumber is divisible by 4.
Try it like this.
String binaryNumber = "110101111";
// first make certain the binary string is a multiple of length four so
// pad on the left with 0 bits.
binaryNumber = "0".repeat(3 - (binaryNumber.length()+3) % 4)
+ binaryNumber;
// Then you can just split it like this as you described.
String[] groups = binaryNumber.split("(?<=\\G.{4})");
for (String v : groups) {
System.out.println(v);
}
prints
0001
1010
1111
For example, I would like to convert the int value 12 into a String output of BCD: 00 12 (0x00 0x12).
If I have int value of 256, it will be 02 56 (which is 0x02 0x56),
or if I have a int value of 999, it will be 09 99 (0x09 0x99),
9999 would be 99 99 (0x99 0x99).
Right now, my only solution is to create a String array of size 4, and calculate how many characters are there by converting the int value into String. If there are 2 characters, I will add 2 x 0 into the array first before adding the 2 characters, and then make them back into a single String variable.
Basically,
int value = 12;
String output = Integer.toString(value);
// then count the number of characters in the String.
// 4 minus (whatever number of characters in the String, add zeros
// add the characters:
stringArray[0] = "0";
stringArray[1] = "0";
stringArray[2] = "1";
stringArray[3] = "2";
// then, concatenate them back
If there are 3 characters, I will add one 0 into the array first before adding 3 characters. I was wondering if there is any other way?
You can use String.format to append leading 0 and use substring to split in to two part.
int value = 12;
String output = String.format("%04d",value);
System.out.println(output.substring(0,2)+" "+output.substring(2,4));
String.format("%04d",value) will append 0s in the front if the length is less than 4.
If you do not want to use substring you can use String.split and String.join like below.
System.out.println(
String.join(
" ",
Arrays.asList(
output.split("(?<=\\G.{2})")
)
)
);
output.split("(?<=\\G.{2})") will split the string in 2 characters each.
Is that what you are asking for?
public static String formatTheString(String string, int length) {
return String.format("%"+length+"s", string).replace(' ', '0');
}
and pass the values like
formatTheString(Integer.toString(256),4);
I think what you are asking is not correct.
refer this for BCD.
and below code is sufficient for what you need
System.out.printf("%04d",n);
in above code n is your number.
I am generating a password which will have 6 to 10 digit.
This is my code which gives me random password of 6-10 digit,
val AB = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:<=>?#_!#%&()*+,-.~";
val rnd = new Random();
def randomPassword(): String = {
val len = rnd.nextInt(5) + 5
val sb = new StringBuilder(len);
for (i <- 0 to len)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
It works fine but the problem is that sometimes it gives all numbers or alphabets.
I want the combination of alphabets and number and special character every time. any suggestion?
Here is a more idiomatic solution to the problem which provides a better API.
object password {
import scala.util.Random
import scala.collection.immutable.Stream
private def gen = Random.alphanumeric
def get(len: Int): String = {
def build(acc: String, s: Stream[Char]): String = {
if (s.isEmpty) acc
else build(acc + s.head, s.tail)
}
build("", gen take len)
}
}
Lets generate some passwords
1 to 25 foreach { _ => println(password get 8) }
You will see something like
YBk2UrOV
GD4eLexS
l8yxAkp9
ooQnaRpd
NgHAruB8
pMXpi4ad
Note: this solution can go a couple of optimization rounds. E.g. #tailrec, StringBuilder.
def randomPassword(): String = {
val len = rnd.nextInt(5) + 5
val sb = new StringBuilder(len);
for (i <- 0 to len)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
if(sb.toString is allString or allNum){
return randomPassword();
}
return sb.toString();
}
The simple solution imho would be (pseudo code)
generate password
if no alphabet;
if not max length;
add an alphabet
else
change last letter with an alphabet
if no digit;
if not max length;
add an digit
else
change first letter with an digit
if no special;
if not max length;
add an special
else
change second letter with an special
This never reduce entropy unless you already have a max length password.
Generate a random password of all letters first, then replace some of the letters with numbers/special characters as you desire.
(By the way, I'm not familiar with Scala, so I'm going to use Java's syntax, as I wouldn't know whether I'm typing something valid otherwise. My apologies.)
// Split source string into letters, numbers, and specials
String AB = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String numbers = "0123456789";
String specials = ":<=>?#_!#%&()*+,-.~";
String randomPassword() {
StringBuilder sb = new StringBuilder();
int len = rnd.nextInt(5) + 5;
// Generate password with letters first. This part is the same as the original code.
for (int i = 0; i <= len; i++) {
sb.append(AB.charAt(rnd.nextInt(AB.length())));
}
// Generate an index to replace with a number
int numberIndex = rnd.nextInt(len);
// Generate an index to replace with a special character
int specialIndex;
do {
specialIndex = rnd.nextInt(len);
} while (specialIndex == numberIndex);
// Replace one letter with a number
sb.setCharAt(numberIndex, numbers.charAt(rnd.nextInt(numbers.length())));
// Replace one letter (or the number if you're unlucky) with a special character
sb.setCharAt(specialIndex, specials.charAt(rnd.nextInt(specials.length())));
}
It's a start, and has a flaw (only one number + special character), but it is easily fixable. This solution is also more efficient than generating entirely new passwords if one does not satisfy your criteria, and you're guaranteed to get a password that works when the method returns.
Using immutable data structures is more idiomatic to scala. The following code works.
protected def nextChar(): Char = Random.nextPrintableChar()
def randomString(length: Int = 10): String = {
(0 until length).map(_ => nextChar()).mkString
}
edit:
To ensure there's always a number, special character, and alphabet in string, i would generate each category of letters separately then randomly concatenate them in a functional way or simply with Random.shuffle(characterList).mkString =D.
You could do apply the principle of the while loop.
Store the appended password into a variable.
Use a while loop to check if it doesn't contain a number and/or symbol, if it doesn't, regenerate the password again and store it into the variable.
When the while loop breaks automatically, return the variable.
You can try this one, it works for me.
$length = 45;
$chars = array_merge(range(0,9), range('a','z'), range('A','Z'));
shuffle($chars);
$password = implode(array_slice($chars, 0, $length));
echo "This is the password: ".$password;
An example of output:
This is the password: wmU7KaZoOCIf4qn2tz5E06jiQgHvhR9dyBxrFYAePcDWk
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.
I need to write a program where the program would generate random letter and i would need to store this random character into an array
char[] arrayRandom = new char[10];
for (int i = 0; i < 8; i++) {
randomNumLet = (generator.nextInt(20) + 1);
System.out.print(arrayRandomLetter[randomNumLet] + " ");
arrayRandomLetter[randomNumLet] = arrayRandom[i];
}
is there anything wrong with my code?
because when i run this and printed the array i get boxes for all the values in the array and there are some letter that this line of code cannot print
System.out.print(arrayRandomLetter[randomNumLet] + " ");
Thanks
You're assigning an element of arrayRandomLetter a value from arrayRandom. As you never initialize arrayRandom, its values are all 0. 0 is not the value of a printable character, hence the boxes.
An easy way to pick a random character is like this:
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char randomChar = chars.charAt(random.nextInt(chars.length()));
You are trying to print arrayRandomLetter before it is assigned.
I'm not going to give you the answer, but I will give you a hint:
(char)('A' + 1) is 'B'
#fastcodejava's answer explains why you are seeing "boxes" -- rendering the ASCII NUL character.
#Mark Peters is also correct, but that's not the simplest solution.