Generate a random string from another string - java

I want to input a string "abcde12345ABCDE" using scanner and then generate a random string of length 4 with the following requirements:
1st place it should be a character
2nd place it should be a number
3rd place it should be a number
at 4th place it should also be character
Example run:
Input
abcde12345ABCDE
\\Processing....
Output
A25b
Then I also want to be prompted to match the generated number.
Plz enter the generated no.!!
A25b
Here is the code I have used to generate a random string
final String alphanumeric = "abcde12345ABCDE";
final int n = alphanumeric.length();
Random r = new Random();
for(int i = 0; i < 4; i++) {
System.out.println(alphanumeric.charAt(r.nextInt(n)));
}

public static void main(String[] args) {
final String alphanumeric = "abcde12345ABCDE";
List<Character> digits = getPart(alphanumeric, true);
List<Character> letters = getPart(alphanumeric, false);
Random r = new Random();
System.out.print(letters.get(r.nextInt(letters.size())));
System.out.print(digits.get(r.nextInt(digits.size())));
System.out.print(digits.get(r.nextInt(digits.size())));
System.out.print(letters.get(r.nextInt(letters.size())));
}
public static List<Character> getPart(String src, boolean numbers) {
List<Character> result = new ArrayList<>();
for (int i = 0; i < src.length(); i++) {
if (numbers == Character.isDigit(src.charAt(i))) {
result.add(src.charAt(i));
}
}
return result;
}

Related

Replacing String in Java to get all variations

I'm trying to get a printout of all variations of a certain String. For example, we have this input: AB0C0. The 0 in the 3rd and 5th spots should be treated as variables. The variable characters are 1, 2, and 3 to be placed in the spot of 0. This means there would be all possible variations of this input:
AB1C1
AB2C1
AB3C1
AB1C2
AB1C3
AB2C2
AB2C3
AB3C2
AB3C3
This is just an example. A 5-character long string is a place for 1 to 5 variables. The issue I'm facing is, that it should generate all variations no matter how many variables are in the input in no matter in which place they are.
Scanner scanner = new Scanner (System.in);
System.out.println("Enter the key consisting of 5 characters:");
String input = scanner.next();
String strOutput1 = input.replaceFirst("0","1");
String strOutput1A = input.replace("0","1");
String strOutput2 = input.replaceFirst("0","2");
String strOutput3 = input.replaceFirst("0","3");
String strOutput4 = input.replaceFirst("0","4");
String strOutput5 = input.replaceFirst("0","5");
System.out.println(strOutput1.toUpperCase());
System.out.println(strOutput1A.toUpperCase());
System.out.println(strOutput2.toUpperCase());
System.out.println(strOutput3.toUpperCase());
System.out.println(strOutput4.toUpperCase());
System.out.println(strOutput5.toUpperCase());
What about this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the key consisting of 5 characters:");
String input = scanner.next();
//find positions of '0' in input
List<Integer> varPositions = findVarPositions(input);
//create permutations
List<String> permutations = new ArrayList<>();
permutations.add(input);//AB0C0
for (int position : varPositions) {
permutations = permutateAtPosition(permutations, position);
}
//print permutations
for (String permutation : permutations) {
System.out.println(permutation.toUpperCase());
}
}
private static List<Integer> findVarPositions(String input) {
List<Integer> varPositions = new ArrayList<>();
int lastVarPosition = -1;
while ((lastVarPosition = input.indexOf('0', lastVarPosition + 1)) != -1) {
varPositions.add(lastVarPosition);
}
return varPositions;
}
private static List<String> permutateAtPosition(List<String> partialyPermutated, int position) {
List<String> result = new ArrayList<>();
char[] replacements = {'1', '2', '3', '4', '5'};
for (String item : partialyPermutated) {
for (int i = 0; i < replacements.length; i++) {
String output = replaceCharAt(item, position, replacements[i]);
result.add(output);
}
}
return result;
}
private static String replaceCharAt(String input, int position, char replacement) {
//converting to char array, because there's no method like
//String.replaceAtPosition(position, char)
char[] charArray = input.toCharArray();
charArray[position] = replacement;
return new String(charArray);
}
}
It's not fixed to a number of variables.
The idea is to extract positions of '0' and subsequently call the method permutateAtPosition, which takes a partially permutated list and permutates it by one more level.
For "a0b0c0" and values 1-2 it would be ['a0b0c0'], then ['a1b0c0','a2b0c0'], then ['a1b1c0','a1b2c0','a2b1c0','a2b2c0'], and finally ['a1b1c1','a1b1c2','a1b2c1','a1b2c2','a2b1c1','a2b1c2','a2b2c1''a2b2c2'].
This solution keeps everything in memory, so in the general case (unlimited input string) it would be wiser to go with depth-first instead.
I've got another solution for you.
First step, getting the amount of variables:
int variableCount = 0;
for (int i = 0; i < 5; i++) {
if (input.charAt(i) == '0') {
variableCount++;
}
}
Then calculating the amount of results we are expecting:
int countMax = (int)Math.pow(4,variableCount);
Lastly, count up in base 4. Pad the number with 0's and replace the original input 0's:
for (int i = 0; i < countMax; i++) {
String paddedNumbers = format("%" + variableCount + "s",Integer.toString(i, 4)).replace(" ", "0");
int replacedCount = 0;
char[] outputChars = input.toCharArray();
for (int j = 0; j < 5; j++) {
if (input.charAt(j) == '0') {
outputChars[j] = paddedNumbers.charAt(replacedCount);
replacedCount++;
}
}
System.out.println(outputChars);
}

Trouble trying to find a word in a String array

For the code, it wakes a user input and splits it by witespaces then takes the individual words from the user input and checks to see if the singular word is in the text file( containing parallel arrays with one being a string array and the other an int array). For every time it finds the user inputted word it needs to add one but the problem is that I don't know how to implement either match, or compare or equalsTo to check to see if the word is in the String array.
public class MovieReviewSentimentAnalysis {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// TODO: complete me
//make own arrays to pass by value
//movieReviewComments = the text
String[] movieReviewComments = new String[10000];
//movieReviewScores = numeric values, avoid lit. values
int[] movieReviewScores = new int[10000];
String userComment = "";
// String reviewFile = "";
// reviewFile = args[0];
String whiteComment = "";
MovieReviewReader.readMovieReviews("movie_reviews.txt", movieReviewComments, movieReviewScores); //string, string array, and int array
System.out.println("Please type one line of review and when you are done press either Ctr D or Ctr Z");
userComment = userInput.nextLine();
System.out.println(userComment);
String[] words2 = userComment.split("[\\W]");
double itemCount = 0;
double wordTotal = 0;
double totalSumOfUserCommentWords = 0;
String test = "";
// int itemCount = words.length;
for (int i = 0; i < words2.length; i++)
{
test = words2[i];
itemCount = wordCount(test, movieReviewComments, movieReviewScores);
wordTotal += itemCount;
totalSumOfUserCommentWords = wordTotal / userComment.length();
// System.out.println(totalSumOfUserCommentWords);
}
// System.out.println(reviewFile);
System.out.println("Incomplete assignment");
userInput.close();
}
public static double wordCount(String test, String[] movieReviewComments, int[] movieReviewScores)
{
double storeScore = 0;
double totalSumofReviewScores = 0;
double numOfTimesWordAppears = 0;
for (int i=0; i < (movieReviewComments.length); i++)
{
if (test.equals(movieReviewComments[i])) //////////////////////////////////////////////////////////SOMETHING'S OFF
{
storeScore = movieReviewScores[i];
totalSumofReviewScores += storeScore;
numOfTimesWordAppears++;
System.out.println("Found"); //QUQ when will you appear!?!?
}
else
System.out.println("You dun goofed"); //delete after fixing problem
}
double wordScoreAverage = totalSumofReviewScores / numOfTimesWordAppears;
return wordScoreAverage;
}
It is very simple. You can do it the following way:
if (movieReviewComments[i].toLowerCase().contains(test.toLowerCase())
And if you want to test an equal comparison and not containment, use following instead:
if (test.equalsIgnoreCase(movieReviewComments[i])

Randomizing a string in Java

I need to, using an already defined set of 2-4 letters, create a string that is completely randomized. How would one take letters, combine them into one string, randomize the position of each character and then turn that large string into two randomly sized (but >= 2) other strings. Thanks for everyone's help.
My code so far is:
//shuffles letters
ArrayList arrayList = new ArrayList();
arrayList.add(fromFirst);
arrayList.add(fromLast);
arrayList.add(fromCity);
arrayList.add(fromSong);
Collections.shuffle(arrayList);
But I found that this shuffles the Strings and not the individual letters. It also, being an array, has the brackets that wouldn't be found in regular writing and I do want it to look like a randomish assortment of letters
This is a pretty brute force approach, but it works. It shuffles index positions and maps them to the original position.
final String possibleValues = "abcd";
final List<Integer> indices = new LinkedList<>();
for (int i = 0; i < possibleValues.length(); i++) {
indices.add(i);
}
Collections.shuffle(indices);
final char[] baseChars = possibleValues.toCharArray();
final char[] randomChars = new char[baseChars.length];
for (int i = 0; i < indices.size(); i++) {
randomChars[indices.get(i)] = baseChars[i];
}
final String randomizedString = new String(randomChars);
System.out.println(randomizedString);
final Random random = new Random();
final int firstStrLength = random.nextInt(randomChars.length);
final int secondStrLength = randomChars.length - firstStrLength;
final String s1 = randomizedString.substring(0, firstStrLength);
final String s2 = randomizedString.substring(firstStrLength);
System.out.println(s1);
System.out.println(s2);
You can build a string and then shuffle the characters from that string. Using Math.rand() you cano generate a random number within the range of the character's length. Generating it for each character will get you the shuffled string. Since your code is unclear, I will just write an example
public class ShuffleInput {
public static void main(String[] args) {
ShuffleInput si = new ShuffleInput();
si.shuffle("input");
}
public void shuffle(String input){
List<Character> chars = new ArrayList<Character>();
for(char c:input.toCharArray()){
chars.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(chars.size()!=0){
int rand = (Integer)(Math.random()*characters.size());
output.append(characters.remove(rand));
}
System.out.println(output.toString());
}
}

Displaying a string with hidden characters

I have a test for a class that displays a word randomly chosen from an array.
I'm trying to display the word with several chars hidden
I have taken the string, then converted it to an array of chars, but I'm confused as to where to go from here.
import java.util.Scanner;
public class wordTest {
public static void main (String args[])
{
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
char[] stringArray;
String [] gamewords = { "dog", "cat", "coffee", "tag", "godzilla", "gamera", "lightning", "flash", "spoon", "steak", "moonshine", "whiskey", "tango", "foxtrot", "ganymede"
, "saturn", "enterprise", "reliant", "defiant", "doom", "galapagos", "jidai", "sengoku"};
arrayWords wl = new arrayWords();
// Words w = new Words();
Word n = new Word();
int a = 0;
int b = gamewords.length;
RandNum rand = new RandNum(a,b);
n.setWord(gamewords[rand.nextRandomIntegerInRange()]);
stringArray = n.getWord().toCharArray();
int blank1 = 1;
int blank2 = 4;
RandNum blanks = new RandNum(blank1,blank2);
n.setWord(gamewords[rand.nextRandomIntegerInRange()]);
do{
int i = 0;
//scanner.nextLine();
for( i = 0; i < stringArray.length; i++){
for( i = 0 ; i < blanks.nextRandomIntegerInRange() ; i++ ){
stringArray[i] = '*';
}
System.out.println(stringArray[i]);
}
}while(scanner.nextLine().equals(""));
}
}
Since you haven't given clear definition on what you want to do, here I assume for every string, you are randomly masking 2 characters, in pseudo code, it looks like:
if inputString.length < 2 {
mask all character
} else {
loop until 2 character masked {
r = random from 0 to inputString.length-1
if (inputString[r] is not masked) {
set inputString[r] to mask character
}
}
}
some hints:
to make "inputString" modifiable, make use of a StringBuilder
Way to check if certain position is masked, you can either simply check if the character in the string == mask character, or you can use a Set to keep all masked position
In order to find out number of position masked, you can keep a counter, or simply use the size of the Set in 2 if you choose to use a Set.
Okay, so I think I've found the solution:
for (int i = 0; i < stringArray.length ; i++) {
stringArray[blanks.nextRandomIntegerInRange()] = '_';
System.out.print(stringArray[i] + " " );
}

Randomize the letters in the middle of the word, while keeping the first and last letters unchanged

import java.util.Scanner;
/**
*
* #author Cutuk
*/
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String a;
Scanner in = new Scanner (System.in);
a = in.nextLine();
char first = a.charAt(0);
System.out.print(first);
int v= a.length()-1;
char last = a.charAt(v);
int k= a.length();
int random=0;
char x='\u0000';
char middle= '\u0000' ;
for (int i=1; i<a.length()-1;i++){
random= (int )(Math.random() * (k-2) + 1);
middle=a.charAt(random);
x=middle;
System.out.print(x);
}
System.out.print(last);
}
}
I am supposed to take a word, shuffle the letters inside, but keep the first and the last letter unchanged. I managed to randomize, but I cannot keep it from repeating.
Your approach is incorrect: when you pick middle letters at random, it is impossible to guarantee that all letters from the middle of the word would be printed (and as a consequence, that other letters would not be repeated).
There are several ways of fixing this:
Each time you generate a random index, mark that index in an array of booleans. The length of the array is equal to the length of the word. Check the array before using each new index that you generate; if the index is marked, continue generating new random indexes until you hit an empty one.
Create an array of integer indexes of letters inside the word (i.e. 1 through length-1, inclusive). Do a random shuffle on the array, and use the shuffled indexes to pick middle letters.
Similar to 2, except you put all middle letters in an array, and shuffle it.
If I understand your question, I would suggest you start by building a List<Character> and then use Collections.shuffle(List) and finally build your return String with a StringBuilder like
private static String shuffleLetters(String in) {
if (in == null || in.length() < 3) {
return in;
}
char first = in.charAt(0);
char last = in.charAt(in.length() - 1);
List<Character> chars = new ArrayList<>();
for (char ch : in.substring(1, in.length() - 1).toCharArray()) {
chars.add(ch);
}
Collections.shuffle(chars);
StringBuilder sb = new StringBuilder();
sb.append(first);
for (char ch : chars) {
sb.append(ch);
}
sb.append(last);
return sb.toString();
}
Assuming "shuffling" can allow a middle character to sometimes be swapped with itself, you can do something like:
private static final String[] TEST_WORDS = {"apple", "banana", "pear", "raspberry", "cucumber", "watermelon", "a", "ab", "", null};
public static void main(String[] args)
{
for (String word: TEST_WORDS)
{
System.out.println(shuffleInside(word));
}
}
private static String shuffleInside(String word)
{
String ret = word;
if (word != null)
{
Random r = new Random();
int strLen = word.length();
if (strLen > 2)
{
char[] middleChars = word.substring(1, strLen - 1).toCharArray();
shuffle(middleChars, r);
ret = word.charAt(0) + new String(middleChars) + word.charAt(strLen - 1);
}
}
return ret;
}
private static void shuffle(char[] chars, Random r)
{
for (int i = chars.length - 1; i > 0; i--)
{
int index = r.nextInt(i + 1);
char c = chars[index];
chars[index] = chars[i];
chars[i] = c;
}
}
Which handles the case where the word is null, one character, two characters, or two or more characters and produces the following output on a single run:
apple
bnaana
paer
rerrsbpay
cbuemucr
waomteerln
a
ab
null
You could simply create a List<Integer> for storing the random numbers that you generated.
Here is your code from above, cleaned up, with meaningful naming and the List for looking up the history:
public class Main {
public static void main(String[] args) {
final Scanner in = new Scanner(System.in);
final Random rnd = new Random(System.currentTimeMillis());
final List<Integer> rndHistory = new LinkedList<>(); // <-- your history
System.out.print("Please type a word: ");
final String input = in.nextLine();
System.out.print(input.charAt(0));
for (int i = 1, random = 0; i < input.length() - 1; i++) {
do {
random = rnd.nextInt(input.length() - 2) + 1;
} while (rndHistory.contains(random)); // check the history
rndHistory.add(random); // add to the history
System.out.print(input.charAt(random));
}
System.out.println(input.charAt(input.length() - 1));
}
}
Main differences:
final Random rnd = new Random(System.currentTimeMillis()); Using
the the java.util.Random class is a better way for generating
random numbers.
final List<Integer> rndHistory = new LinkedList<>(); This is the actual difference, part of the mechanism to prevent double shuffles
System.out.print("Please type a word: "); a meaningful prompt for
the user (who is going to know what to do, when you program is
executed and there is nothing on the screen?)
and finally:
do {
random = rnd.nextInt(input.length() - 2) + 1;
} while (rndHistory.contains(random)); // check the history
rndHistory.add(random); // add to the history
The 'prevent a random number from being used twice' mechanics
For your random try this: Random generator = new Random(System.currentTimeMillis());

Categories

Resources