Adding probability without adding more to StringArray - java

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

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;

Java - Improper Checking in For Loop

This is a chunk of code in Java, I'm trying to output random numbers from the tasks array, and to make sure none of the outputs are repeated, I put them through some other loops (say you have the sixth, randomly-chosen task "task[5]"; it goes through the for loop that will check it against every "tCheck" element, and while task[5] equals one of the tCheck elements, it will keep trying to find another option before going back to the start of the checking forloop... The tCheck[i] elements are changed at the end of each overall loop of output to the new random number settled on for the task element).
THE PROBLEM is that, despite supposedly checking each new random task against all tCheck elements, sometimes (not always) there are repeated tasks output (meaning, instead of putting out say 2,3,6,1,8,7,5,4, it will output something like 2,3,2,1,8,7,5,4, where "2" is repeated... NOT always in the same place, meaning it can sometimes end up like this, too, where "4" is repeated: 3,1,4,5,4,6,7,8)
int num = console.nextInt();
String[] tasks = {"1","2","3","4","5","6","7","8"};
String[] tCheck = {"","","","","","","",""};
for(int i = 0; i<= (num-1); i++){
int tNum = rand.nextInt(8);
for(int j = 0; j <=7; j++){
if(tasks[tNum].equals(tCheck[j])){
while(tasks[tNum].equals(tCheck[j])){
tNum = rand.nextInt(8);
}
j = 0;
}
}
tCheck[i] = tasks[tNum];
System.out.println(tasks[tNum]+" & "+tCheck[i]);
}
None of the other chunks of code affect this part (other than setting up Random int's, Scanners, so on; those are all done correctly). I just want it to print out each number randomly and only once. to never have any repeats. How do I make it do that?
Thanks in advance.
Firstly, don't use arrays. Use collections - they are way more programmer friendly.
Secondly, use the JDK's API to implement this idea:
randomise the order of your elements
then iterate over them linearly
In code:
List<String> tasks = Arrays.asList("1","2","3","4","5","6","7","8");
Collections.shuffle(tasks);
tasks.forEach(System.out::println);
Job done.
you can check if a certain value is inside your array with this approach.
for(int i = 0; i<= (num-1); i++){
int tNum = rand.nextInt(8);
boolean exist = Arrays.asList(tasks).contains(tNum);
while(!exist){
//your code
int tNum = rand.nextInt(8);
exist = Arrays.asList(tasks).contains(tNum);
}
}
if you are using an arraylist then you can check it with contains method since you are using an array we have to get the list from the array using asList() and then use the contains method. with the help of the while loop it will keep generating random numbers untill it generates a non duplicate value.
I used to created something similar using an ArrayList
public class Main {
public static void main(String[] args) {
String[] array = { "a", "b", "c", "d", "e" };
List<String> l = new ArrayList<String>(Arrays.asList(array));
Random r = new Random();
while(!l.isEmpty()){
String s = l.remove(r.nextInt(l.size()));
System.out.println(s);
}
}
}
I remove a random position in the list until it's empty. I don't use any check of content. I believe that is kind of effective (Even if I create a list)

Unable to use Set to remove duplicate pair numbers

Let's say I want to generate 20 random numbers on a 8 by 6 grid.(8 columns, 6 rows) . Based on the answer from here:Creating random numbers with no duplicates, I wrote my code like this:
Random randomNumGenerator = new Random();
Set<Integer[][]> generated = new LinkedHashSet<Integer[][]>();
while (generated.size() < 20) {
int randomRows = randomNumGenerator.nextInt(6);
int randomColumns = randomNumGenerator.nextInt(8);
generated.add(new Integer[][]{{randomRows,randomColumns}});
}
In reality what happens is the Set see Integer[][]{{5,5}}; and Integer[][]{{5,5}};as NOT duplicate.Why? Even tho my purpose is to get 20 non-duplicate pair of numbers, this does not work. How do I fix this?
The Set checks for duplicates using the equals method (and also the hashCode method) of its inner type, but the Integer[][]'s equals method compares the memory addresses and not the contents.
Why do you use a Set of Integer[][] if you just want to store pairs?
Unfortunately, in Java there is no Pair class, but if you do not want to create your own, you can use the Map.Entry for that.
Random randomNumGenerator = new Random();
Set<Map.Entry<Integer, Integer>> generated = new LinkedHashSet<>();
while (generated.size() < 20) {
int randomRows = randomNumGenerator.nextInt(6);
int randomColumns = randomNumGenerator.nextInt(8);
generated.add(new AbstractMap.SimpleEntry<>(randomRows,randomColumns));
}
System.out.println(generated);
Array equals is == in Java, so an array is only equal to itself. Normaly you use Arrays.equals(array1, array2) to compare them by content, but in this case, arrays are simply the wrong choice. You can either create a bean, as rafalopez79 suggested of use an array of Collections (List in your case), as a List will compare the content on equals, see the documentation. Choice is pretty much yours, a bean would probably be a bit cleaner.
How about this code. I ran it through the debugger, it works nicely and yes, the contains() method checks the value of the Integer, not the reference. You can change the range of the random number as needed, I used 5 to facilitate testing. Yes I know it's not very robust, as written this will be an endless loop (because of the limited range of 5) but it's a simple example to make the point.
UPDATE: Actually this has a bug in that it won't check for uniqueness across all the rows, but that's easily fixed as well. I just re-read the original question and looking at the original code I'm not sure I know what you want exactly. If you just want a grid with 48 unique Intergers arranged 8 by 6 this will do it, but there are several ways to do this.
final int rows = 6;
final int cols = 8;
Random randomGenerator = new Random();
ArrayList[] grid = new ArrayList[rows];
for(int i=0; i<rows; i++)
{
grid[i] = new ArrayList<Integer>();
for(int j=0; j<cols; j++)
{
for(;;)
{
Integer newInt = new Integer(randomGenerator.nextInt(5));
if(!grid[i].contains(newInt))
{
grid[i].add(newInt);
break;
}
}
}
}

How to check a matrix postion value in java?

Given a matrix filled in with all its values, there's the need of pulling out data randomly in order to create a random matrix (intialized with null values each position). The issue lies while checking if a position (within the randomMatrix) is different from null, as shown below:
public void randomLogic(String[][] givenMatrix){
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int positioni = this.randInt(0, 1);
int positionj = this.randInt(0, 1);
int x = this.randInt(0, 3);
int y = this.randInt(0, 2);
/*In here lies the reported issue while checking if empty. */
while (!this.randomMatrix[x][y].isEmpty()) {
x = this.randInt(0, 3);
y = this.randInt(0, 2);
this.randomMatrix[x][y] = givenMatrix[positioni][positionj];
}
}
}
}
I've also tried with the following: while(this.randomMatrix[x][y] != null) and the code breaks down right away. All the solving-logic work out as expected (because if I ommit that part it works with flaws but works) the only problem is that validation. Regardless of what position is being evaluated it always stops working.
Is there any other way of checking a matrix position value?
are you trying to pull random values (and consequently, some will be repeated) from a givenMatrix OR do you want to specifically randomize the givenMatrix?
If it's the latter, I would approach it differently.
First of all, gather all values of the givenMatrix in one linear-array or list.
Then, you can randomize this array, and you'll be left with a big array of rows*columns items, with all the values from the original matrix already randomized.
Then, you can systematically fill the new randomized matrix, taking each element of the array in order, till you complete each row and column of the new matrix.
I would choose this approach, because it's easier, and it will finish in a fixed number of steps; rather than filling random positions, because maybe you land 2 times in the same place to fill, and you'll have to randomize until you hit all the spots.
(Also, if you don't care of repeating the values for the new matrix, then instead of taking each element of the randomized array, you can simply pick a random position of this array each time)
Have you declared String[][] randomMatrix as a class level member variable? If you have declared the randomMatrix correctly then the isEmpty() and != null checks should work.

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.

Categories