I have to generate a sequence of strings combination starting with some fixed bits at the beginning, for example,
String password = "abc-----"
Here, the first three characters remain the same for every combination, only the characters after that have to change,
I need various combinations of this string like
abca
abcb
abcc
-----
abcaa
abcab
---- so on
using any loop, so that within the same loop i need to compare this with other input string and output the string, if both match.
How to generate this sequence or various combinations of strings using a loop in Java or in general ?
//update, sorry, i forgot to post what i tried:
i am doing it using nested for loops such as,
for(char i='a'; i<'z'; i++) {
for(char j='a'; j<'z'; j++) {
String password = "abc" + i + j ;
}
}
Is there any more efficient way to do this ?
if you want to generate a random string then you can use: (here i have included numbers also in my random string generation, if you dont want to use numbers then you can remove from sample variable)
public String getRandomString(String prefix, int length) {
String sample = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random random = new Random();
StringBuilder sb = new StringBuilder();
sb.append(prefix);
for (int index = 0; index < length; index++) {
sb.append(sample.charAt(random.nextInt(sample.length())));
}
return sb.toString();
}
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
I am having an array
int arr[]={1,$,2,3,$,$,4,5}
and want the output as
arr[]={1,2,3,4,5,$,$,$}
Can you please help me
My code is
public class ArrayTest
{
static void splitString(String str)
{
StringBuffer alpha = new StringBuffer(),
num = new StringBuffer(), special = new StringBuffer();
for (int i=0; i<str.length(); i++)
{
if (Character.isDigit(str.charAt(i)))
num.append(str.charAt(i));
else
special.append(str.charAt(i));
}
System.out.print(num);
System.out.print(special);
}
public static void main(String args[])
{
String str = "1,2,$,$,3,4";
splitString(str);
}
}
I am getting the O/P as 1234,,$,$,,
instead of 1,2,3,4,$,$
Sorting is not single activity. Sorting is actually ordering, and comparing.
You can use Java built-in sorting but your own comparator (piece of code that knows how to compare).
Your comparator, need to make sure that special sign is just bigger then any other value (and is equal to any other special sign). If neither compared value is special sign, do ordinary comparison.
Here is link to other question that explains how to do that:
How to use Comparator in Java to sort
From your output I can see that your function includes the commas in the sorting as well. You must remove the commas before sorting the String:
str = str.replaceAll(",", "");
This line of code will replace all commas with nothing, or in other words remove them. Now you can execupe your sorting algorithm and add the commas at the end:
String merge = num.toString() + special.toString();
String result = "";
for (int i = 0; i < merge.length(); ++i) {
result += merge.charAt(i) + ",";
}
This will put an additional comma at the end which you can remove very easily:
result = result.substring(0, result.length() - 1);
Now result holds the wanted result.
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
I'm writing a small JAVA program which:
takes a text as a String
takes 2 arrays of chars
What im trying to do will sound like "find and replace" but it is not the same so i thought its important to clear it.
Anyway I want to take this text, find if any char from the first array match a char in the text and if so, replace it with the matching char (according to index) from the second char array.
I'll explain with an example:
lets say my text (String) is: "java is awesome!";
i have 2 arrays (char[]): "absm" and "!#*$".
The wished result is to change 'a' to '!' , 'b' to '#' and so on..
meaning the resulted text will be:
"java is awesome!" changed to -> "j#v# i* #w*o$e!"
What is the most efficient way of doing this and why?
I thought about looping the text, but then i found it not so efficient.
(StringBuilder/String class can be used)
StringBuilder sb = new StringBuilder(text);
for(int i = 0; i<text.length(); i ++)
{
for (int j = 0; j < firstCharArray.length;j++)
{
if (sb.charAt(i) == firstCharArray[j])
{
sb.setCharAt(i, secondCharArray[j]);
break;
}
}
}
This way is efficient because it uses a StringBuilder to change the characters in place (if you used Strings you would have to create new ones each time because they are immutable.) Also it minimizes the amount of passes you have to do (1 pass through the text string and n passes through the first array where n = text.length())
I guess you are looking for StringUtils.replaceEach, at least as a reference.
How efficient do you need it to be? Are you doing this for hundreds, thousands, millions of words???
I don't know if it's the most efficent, but you could use the string indexOf() method on each of your possible tokens, it will tell you if it's there, and then you can replace that index at the same time with the corresponding char from the other array.
Codewise, something like (this is half pseudo code by the way):
for(each of first array) {
int temp = YourString.indexOf(current array field);
if (temp >=0) {
replace with other array
}
}
Put the 2 arrays you have in a Map
Map<Character, Character> //or Map of Strings
where the key is "a", "b" etc... and the value is the character you want to substitute with - "#" etc....
Then simply replace the keys in your String with the values.
For small stuff like this, an indexOf() search is likely to be faster than a map, while "avoiding" the inner loop of the accepted answer. Of course, the loop is still there, inside String.indexOf(), but it's likely to be optimized to a fare-thee-well by the JIT-compiler, because it's so heavily used.
static String replaceChars(String source, String from, String to)
{
StringBuilder dest = new StringBuilder(source);
for ( int i = 0; i < source.length(); i++ )
{
int foundAt = from.indexOf(source.charAt(i));
if ( foundAt >= 0 )
dest.setCharAt(i,to.charAt(foundAt));
}
return dest.toString();
}
Update: The Oracle/Sun JIT uses SIMD on at least some processors for indexOf(), making it even faster than one would guess.
Since the only way to know if a character should be replaced is to check it, you (or any util method) have to loop through the whole text, character after the other. You can never achieve better complexity than O(n) (n be the number of characters in the text).
This utility class that replaces a char or a group of chars of a String. It is equivalent to bash tr and perl tr///, aka, transliterate.
/**
* Utility class that replaces chars of a String, aka, transliterate.
*
* It's equivalent to bash 'tr' and perl 'tr///'.
*
*/
public class ReplaceChars {
public static String replace(String string, String from, String to) {
return new String(replace(string.toCharArray(), from.toCharArray(), to.toCharArray()));
}
public static char[] replace(char[] chars, char[] from, char[] to) {
char[] output = chars.clone();
for (int i = 0; i < output.length; i++) {
for (int j = 0; j < from.length; j++) {
if (output[i] == from[j]) {
output[i] = to[j];
break;
}
}
}
return output;
}
/**
* For tests!
*/
public static void main(String[] args) {
// Example from: https://en.wikipedia.org/wiki/Caesar_cipher
String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
String from = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String to = "XYZABCDEFGHIJKLMNOPQRSTUVW";
System.out.println();
System.out.println("Cesar cypher: " + string);
System.out.println("Result: " + ReplaceChars.replace(string, from, to));
}
}
This is the output:
Cesar cypher: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD
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.