Change random character in string - java

Good time of the day
I have to implement some functions on my site.
When a user enters the website, he has to enter a number of errors that should be occurred in some string. If he chooses 0, the original string will be displayed without error. If the user enters 1 in the error field, the string should be displayed with 1 error. For instance, the word "programming" should be displayed like "rrograming" or "prugramming", or adding/deleting one character to/from the string. Consequently, if the error is 2, the mistakes also should be 2.
In addition, the result should be the same every time. Someone told me to use seeds in Random class, but now I don't have idea.
I am programming in Java and some JS
Please, if you faced the same problem or experience, give me some ideas or resources to learn.

Random with a seed results in the same sequence of values every time, so use the same random every time.
The trick is using a random seed based on the word content. Otherwise you would end up doing the same mutilation pattern on all words.
The likeliness of changing a letter can be in the order of the length of the word.
And inserting twice as much as removing, both rare.
String mutilateWord(String word, int times) {
//Random random = new Random(42);
// Or better (as different words get differently mixed up:
Random random = new Random(word.hashCode());
for (int t = 0; t < times; ++t) {
int chars = word.length;
// If a letter modification has the same likeliness:
int choices = chars + 2 + 1; // change some letter + (twice) add + remove
word = switch (random.nextInt(choices)) {
case 0 -> removeRandomLetter(word, random);
case 1, 2 -> insertRandomLetter(word, random);
default -> changeRandomLetter(word, random);
};
}
return word;
}
Since java 12 one can use a switch expression as above.
The above will also mutilate the mutilations, so you might prefer to first have a times loop changing random letters (or not), and then a second times loop adding/removing letters.

Your friend's idea is correct, setting the random number seed to the same value each time will yield same results. However, you can cache the result everytime you compute it in a map for example. Setting the keys as the error number and the value as the string result. On each function call you check if the error number is cached, if that's the case you return it without computing it else you compute the result then cache it and finally return it.

Related

ArrayList with formatting

Struggling with my ArrayList code.
I needed to generate 20 random numbers between 1 and 200.
It works but when I show all in array list it, it all comes out horizontal
(ie: [190.9873874849,3.45694033,67.900034...] and SUPER long. It needs to have each number print out in a list format, with the only four digits after the decimal. (%10.4)
I tried this:
System.out.printf("%10.4", num[0]);
which works for the formatting but I can't seem to get the whole arraylist to work.
My array is this:
ArrayList<Number> num = new ArrayList<Number>();
for (int i = 0; i<20; i++) {
num.add(Math.random() *200 +1);
}
It works like I said for getting and listing the numbers -- but not in the "correct" way.
I also have to save the numbers to a file, and be able to let the user choose an index for them and tell them their number they chose from the file, which I am also struggling with.
Any help would be amazing!!!
[EDIT]
This worked (from Ole V.V.):
for (int i = 0; i<20; i++) {
num.add(Math.random() *200 +1);
System.out.printf("%10.4f%n", num.get(i));
[ADDITIONAL]
**I have to post here and can't make a new question because some jerk downvoted me? **
I have all of the numbers in my array read in and saved to a text file (with the right formatting!) but now I have to be able to ask the user for an index, and be able to find the object according to that index... but it isn't working!
I don't know how to assign indexes to variables when the numbers are no longer in array format (they're in a column similar to what is in the column).
Here are a couple of options. First, you may use a for loop like the one you already have:
for (int i = 0; i < 20; i++) {
System.out.printf("%10.4f%n", num.get(i));
}
A terser option is:
num.forEach(n -> System.out.printf("%10.4f%n", n));
In both case the output goes like
186.8143
129.4201
169.7405
...
Your format string, %10.4, was almost correct. You need to add f for formatting a floating-point number. I also added %n for a line break after the number. In Java num[i] works only for arrays, not for ArrayList, you need num.get(i).
You need to trim the extra digits by this simple trick.
double number = Math.random()*200 + 1;
number = (long)( number * 10000 );
number = number / 10000;

Add a new HashSet to a previous HashSet, "CHANGING" the previous HashSet and continue doing so until certain condition has been met

I know that if you have two HashSet the you can create a third one adding the two.However, for my purpose I need to change my previous HashSet, look for certain condition , and then if not met then change the set again.My purpose is that that I will give an input, say number 456, and look for digits(1 through 9, including 0).If I'm unable to find size 10 for the HashSet then I will multiply the number with 2 , and do the same.So I'll get 912; the size is 6 now(and I need to get all digits 1-9 & 0, i.e., size 10).Now I will multiply it by 3 and I get 2736 , the size is now 7.I keep doing so until I get size 10.At the time I get size 10, I will complete the loop and return the last number that concluded the loop, following the incremental multiplication rule.My approach is as follows.It has errors so won't run but it represents my understanding as of now.
public long digitProcessSystem(long N) {
// changing the passed in number into String
String number = Long.toString(N);
//splitting the String so that I can investigate each digit
String[] arr = number.split("");
// Storing the digits(which are Strings now) into HashSet
Set<String> input = new HashSet<>(Arrays.asList(arr));
// Count starts for incremental purpose later.
count =1;
//When I get all digits; 1-9, & 0, I need to return the last number that concluded the condition
while (input.size() == 10) {
return N;
}
// The compiler telling me to delete the else but as a new Java user so far my understanding is that I can use `else` with `while`loops.Correct me if I'm missing something.
else {
// Increment starts following the rule; N*1, N*2,N*3,...till size is 10
N = N*count;
// doing everything over
String numberN = Long.toString(N);
String[] arr1 = number.split("");
// need to change the previous `input`so that the new updated `HashSet` gets passed in the while loop to look for size 10.This is error because I'm using same name `input`. But I don't want to create a new `set` , I need to update the previous `set` which I don't know how.
Set<String> input = new HashSet<>(Arrays.asList(arr1));
// increments count
count++;
}
clear() input and add the new values. Something like
// Set<String> input = new HashSet<>(Arrays.asList(arr1));
input.clear();
input.addAll(Arrays.asList(arr1));
and
while (input.size() == 10) {
should be
if (input.size() == 10) {
Or your else isn't tied to an if.

Create A Method In Java

Hello I am trying to create a method in Java that Accepts an integer from the user. Calculate and display how many occurences of the integer are in the array(i'm Creating a random array) as well as what percentage of the array values is the entered integer.
This is how i create my Array:
public void fillVector ( )
{
int myarray[] = new int [10];
for (int i = 0 ; i < 10 ; i++)
{
myarray [i] = (int) (Math.random () * 10);
}
}
Any sugestions how can i do to accomplish this ?
This seems like a homework to you so I am not gonna give you the full solution but I will break down the steps of what you need to do in order to solve your problem. You have to find out how to code those steps yourself, or at least provide some code and your specific problem because your question is too vague right now.
Ask the user to input the number.
Store that number somewhere.
Check each cell of the array for that number. If you find one appearance
increase the counter and continue until the end of your index.
Print out the appearances of the given number.
Print out the percentage of the cells containing the given value to the total amount of cells.
As I can see from your code (if it's yours) you are capable to pull this off on your own. It shouldn't be too hard.

Adding probability without adding more to StringArray

I got this string[] I use in a grid of these images. The grid is generated randomly using a random. now I use the way of just adding the one object more times. but my algorithm to regenerate one if two pictures are the same(eg. egg-tree-blackcar-blackcar-pinkcar) won't work because I check the array indexes of the images.
String bingoObject[] = {
"black_car",
"gray_car",
"white_car",
"red_car",
"yellow_car",
"blue_car",
"pink_car",
"green_car",
"boat",
"tree",
//ADDED MORE FOR CHANCES
"black_car",
"black_car",
"gray_car",
"white_car",
"red_car",
"blue_car",
"green_car"
};
Is there another way to get randoms and assigning probability to each object without having to add them more times into the array? This would clean and help me through a lot of messy coding.
I don't personally know of any ways to assign probability, but we can kind of create our own way. It's not the most efficient way of doing so, but it does create a pseudo-probability.
int [] numbers = {1,2,3,4,5,6,7,8,9,10};
int index = 0;
Random rnd = new Random();
for (int i = 0; i < 3; i ++)
{
index = index + rnd.nextInt(numbers.length);
}
index=index/3;
System.out.println(numbers[index]);
This will skew the array index to be somewhere near the middle, most of the time. So the most common values, in theory, will be near the middle of the array, while the borders will be very uncommon.
You can change the "3" value to be whatever you want, the higher this number is, the more middle-biased the numbers should be.
Upon running this 10 times, my values were:
2,6,7,2,6,5,6,6,4,5

Java boolean if question

I am making a lottery program where I am asking if basically they would like a quick pick ticket. The numbers for their ticket of course would be random since it is a quick pick but the first four numbers range from 0-9 while the fifth number only goes up to 0-4. I am trying to ask them to input a button such as either "1" for no or "2" for yes if they don't want one then it would skip this step. But I am doing the boolean part incorrectly though. Could someone help me out?
Here is an example
System.out.println("Do you want Quick pick, 1 for no or 2 for yes? The first four numbers is from a separate set of 0 to 9 and the fifth number is from a set of 0 to 4.");
QuickPick=keyboard.nextInt();
if((QuickPick==1)){
return false;
}
if((QuickPick==2)){
return true;
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
}
I still haven't gotten around to making the line of code for the final number of 0-4, just the first four numbers, so I haven't forgotten that.
Your code for case 2 immediately does a return true; which ends the method (I assume this is in a method) right then and there. Your other lines don't get execute at all.
Consider using a switch() statement here, it'll make it easier to read:
switch(QuickPick)
{
case 1:
return false;
case 2:
int n = (int)(Math.random()*9+0); // Why is n here? You don't do anything with it?
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
return true;
default:
// Uh oh - someone did something bad maybe just return false?
return false;
}
Also your code for case 2 is definitely wrong, you need to generate a total of five numbers, using bounds 0-9 for the first 4 and 0-4 for the last one. You'll want to use Java's Random to do this (not Math.Random) something like:
Random rand = new Random();
int somethingRandom = rand.nextInt(10);
// Will give you an integer value where 0 < val < 10
// You can call rand.nextInt as many times as you want
To avoid doing your homework for you -- I'll follow the typical CS textbook line and say "Implementation left as an exercise."
The code after return true will not be executed - you need to put that prior to the return statement
Like Marvo said, you dropped a brace in your if.
But you also have faulty logic. I'm not quite sure what the purpose of the method you're in is (that returns a boolean value). But your last few lines will never be reached unless the user types in something like 3 or 42.
Assuming the method is supposed to a) Ask if the user wants a Quick Pick b) Calculate the Quick Pick, if desired c) Return true/false depending on whether the Quick Pick happened or not, you should have:
public boolean doQuickPick()
{
System.out.println("Do you want Quick pick, 1 for no or 2 for yes? The first four numbers is from a separate set of 0 to 9 and the fifth number is from a set of 0 to 4.");
QuickPick=keyboard.nextInt();
if((QuickPick==1)){
return false;
}
if((QuickPick==2)){
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
return true;
}
}
As a separate issue, it'd be much better style to break that into several methods. boolean yesNoPrompt(String message), generateQuickPick(), etc.
Your question is kind of unclear, so I'm afraid I can't be much more help than that. Do post any clarifications / further questions if you have them.
if((QuickPick==2)){
return true;
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
}
In the above copied code from your question, I see that you will be getting compilation errors in your IDE. Your IDE will complain about "Unreachable Code" for the line that is just below the return statement. So, you need to put the return statement at the end of the if block.

Categories