Specifying random chance [duplicate] - java

This question already has answers here:
How to pick an item by its probability?
(13 answers)
Closed 8 years ago.
Now , I will generate random numbers between 1 to 5. I assume there has probability or chance to gain on each number . (please assume for example if you don't agree it)
1 has 20%
2 has 20%
3 has 20%
4 has 20%
5 has 20%
I would like to increase or decrease chances of some numbers as I wish..
1 has 10%
2 has 10%
3 has 35%
4 has 40%
5 has 5%
If so , I can generate random numbers as I wish. Some were hard to get and some will gain frequently.
How can I achieve it by Java ? Please support me with some examples or some useful links or anything else. I would really appreciated it. Please don't be suggest to describe some my efforted codes because I have no idea for this and I request some useful suggestions from you . Thanks in advance.

The solution is simple:
double r = random.nextDouble();
if (r < 0.1) ret = 1
else if (r < 0.2) ret = 2
else if (r < 0.55) ret = 3
...
you get the idea, use the cumulative likelihood as threshold.

First instantiate java.util.Random rand = new java.util.Random();. Do this exactly once.
From there, one approach is to use double f = rand.nextDouble(); which gives you a number between (and including) 0 to (and not including) 1.
Then transform using a series of ifs:
if (f < 0.1){
return 1;
} else if (f < 0.1 + 0.1){
return 2;
} else if (f < 0.1 + 0.1 + 0.35){
return 3;
... /*can you see the pattern*/
It's not quite the fastest way, but is clear and will get you started.

I don't know if there is a way with the Random library.
But I think you can generate a Random number between 1 and 100.
And so, you can code that between:
1 and 10 you obtain 1,
11 and 20 you obtain 2,
21 and 55 you obtain 3,
and so on

An alternative I can think about it is
int[] a = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 5, 5, 5, 5, 5};
Random r = new Random();
return a[ r.nextInt(100) ];

Related

Quicksort went wrong (added some duplicates)

I'm new to sorting algorithms and can't seem to figure out what went wrong. With an unsorted array of int [] uArr = {5,2, 10, 7, 6, 0, 8, 1, 9}, i'm given 0,1,2,5,5,6,8,10 (the nine in the org. array was replaced with a duplicate 5 and the 7 was lost). If I add duplicates to the array, I get more duplicates after the array is sorted and a few more missing numbers.
public static void main(String args[]){
int [] uArr = {5,2, 10, 7, 6, 0, 8, 1, 9};
qSort(uArr, 0, 8);
}
public static void qSort(int [] A, int low, int high){
if (low < high){
int pivotL = partition(A, low, high);
qSort(A, low, pivotL);
qSort(A, pivotL+1, high);
}
}
public static int partition(int [] arr, int low, int high){
int pivot = arr[low];
int leftwall = low;
for (int i = low + 1; i < high; i++){
if (arr[i] < pivot){
int temp = arr[i];
arr[i] = arr[leftwall];
arr[leftwall] = temp;
leftwall += 1;
}
}
int temp2 = pivot;
pivot = arr[leftwall];
arr[leftwall] = temp2;
return leftwall;
}
}
So one thing you should seriously do is start writing documentation. Even though this is a small program, you seem to have forgotten what you were doing as you were writing the code.
For example, there are 9 elements in the array, and you pass in the offsets to sort, inclusive, as 0 through 8:
qSort( uArr, 0, 8 );
But then in the partition routine you only sort elements less than the high value:
for( int i = low + 1; i < high; i++ ) {
And unlike you the last value in the array, 9, is never touched for me and never sorted. So that's an issue. Figure out if you want your indexes to be inclusive or not. For me writing documentation as I go helps me keep these ideas straight.
I'm still looking for other problems like the duplication.
Update: I'm going to just post these as I figure them out, as a sort of stream-of-consciousness of how I look for problems. One thing I was taught early on is that adding print statements to your code can be faster than using a debugger. So (after re-formatting your code, because the formatting you posted was frankly crap) I added this:
public static void qSort( int[] A, int low, int high ) {
System.out.println( Arrays.toString( A ) + " low=" + low + " high=" + high );
And got this output:
run:
[5, 2, 10, 7, 6, 0, 8, 1, 9] low=0 high=8
[2, 0, 1, 5, 6, 5, 8, 10, 9] low=0 high=3
[0, 1, 2, 5, 6, 5, 8, 10, 9] low=0 high=2
[0, 1, 2, 5, 6, 5, 8, 10, 9] low=0 high=0
[0, 1, 2, 5, 6, 5, 8, 10, 9] low=1 high=2
[0, 1, 2, 5, 6, 5, 8, 10, 9] low=1 high=1
[0, 1, 2, 5, 6, 5, 8, 10, 9] low=2 high=2
[0, 1, 2, 5, 6, 5, 8, 10, 9] low=3 high=3
[0, 1, 2, 5, 6, 5, 8, 10, 9] low=4 high=8
[0, 1, 2, 5, 5, 6, 8, 10, 9] low=4 high=5
[0, 1, 2, 5, 5, 6, 8, 10, 9] low=4 high=4
[0, 1, 2, 5, 5, 6, 8, 10, 9] low=5 high=5
[0, 1, 2, 5, 5, 6, 8, 10, 9] low=6 high=8
[0, 1, 2, 5, 5, 6, 8, 10, 9] low=6 high=6
[0, 1, 2, 5, 5, 6, 8, 10, 9] low=7 high=8
[0, 1, 2, 5, 5, 6, 8, 10, 9] low=7 high=7
[0, 1, 2, 5, 5, 6, 8, 10, 9] low=8 high=8
[0, 1, 2, 5, 5, 6, 8, 10, 9]
BUILD SUCCESSFUL (total time: 0 seconds)
I did have to stare at the output for a while, but what I noticed next was two things. The 5 is duplicated almost immediately, and the 5 is also the first element, which means it's going to be chosen by your partition code as the pivot. So it looks as though you have problems re-merging the pivot with the array.
Update 2: OK found another problem. This one I found by writing your array out by hand and walking through each value of i and leftwall as it makes the first partition. Problem here:
When the pivot, 5, encounters the element 0 in the array, the rest of the array has not been sorted. The 10, 7, 6, etc. are not less than the pivot and have not be touched. So when you make the swap, you sawp this:
[2, 5, 10, 7, 6, 0, 8, 1, 9]
for this:
[2, 5, 0, 7, 6, 5, 8, 1, 9]
This is because leftwall was 1 (it had been swapped with the 2 but not any other number, so it only had been incremented once) and there's the duplication and losing numbers too. I'm going to stop there because you have some pretty big problems.
What you need to do in this case is swap the 10, not the pivot, with the 0. This is going to require one additional pointer at least. Quicksort algorithms need to find the lowest and highest in the array and have two loops inside the outer for loop. What you have here is a kind of weird recursive insert sort. You'll need to think a bit more how to do this, but two more loops, nest inside the first, will be required.

Convert String into a two dimensional array

I try to convert this string
s=[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]
into a two dimensional array like this
{4, 2, 2, 4},
{3, 4, 5, 6},
{6, 7, 8,9},
{3, 2, 1, 4}
by use this code
int e=s.replaceAll("\\[", "").replaceAll(" ","").replaceAll("],","]").length();
String[] rows1 = s.replaceAll("\\[", "").replaceAll(" ","").replaceAll("],","]").substring(0, e-2).split("]");
String[][] matrix1 = new String[4][4];
int r1 = 0;
for (String row1 : rows1) {
matrix[r1++] = row1.split(",");
}
System.out.println(Arrays.deepToString(matrix1));
But is have problem like this
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at test.main(test.java:94)
Can you help me find a solution?
I think this code will help you. Read the all comments carefully.
String s="[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]";
s=s.replace("[","");//replacing all [ to ""
s=s.substring(0,s.length()-2);//ignoring last two ]]
String s1[]=s.split("],");//separating all by "],"
String my_matrics[][] = new String[s1.length][s1.length];//declaring two dimensional matrix for input
for(int i=0;i<s1.length;i++){
s1[i]=s1[i].trim();//ignoring all extra space if the string s1[i] has
String single_int[]=s1[i].split(", ");//separating integers by ", "
for(int j=0;j<single_int.length;j++){
my_matrics[i][j]=single_int[j];//adding single values
}
}
//printing result
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(my_matrics[i][j]+" ");
}
System.out.println("");
}
[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]
Logic:
1) replacing all [ to "" now I have-> 4, 2, 2, 4], 3, 4, 5, 6], 6, 7, 8, 9], 3, 2, 1, 4]]
2) Separating all by "]," now I have->
A) 4, 2, 2, 4
B) 3, 4, 5, 6
c) 6, 7, 8, 9
d) 3, 2, 1, 4
3) Separating A B C D by ", " now I have->
A) a) 4 b) 2 c) 2 d) 4
B) a) 3 b) 4 c) 5 d) 6
c) a) 6 b) 7 c) 8 d) 9
d) a) 3 b) 2 c) 1 d) 4
Solution using Java streams:
String[][] arr = Arrays.stream(str.substring(2, str.length() - 2).split("\\],\\["))
.map(e -> Arrays.stream(e.split("\\s*,\\s*"))
.toArray(String[]::new)).toArray(String[][]::new);
Try this...
String s="[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]";
// Split on this delimiter
String[] rows = s.split("], \\[");
for (int i = 0; i < rows.length; i++) {
// Remove any beginning and ending braces and any white spaces
rows[i] = rows[i].replace("[[", "").replace("]]", "").replaceAll(" ", "");
}
// Get the number of columns in a row
int numberOfColumns = rows[0].split(",").length;
// Setup your matrix
String[][] matrix = new String[rows.length][numberOfColumns];
// Populate your matrix
for (int i = 0; i < rows.length; i++) {
matrix[i] = rows[i].split(",");
}
// Display your matrix
System.out.println(Arrays.deepToString(matrix));
Results:
This just doesn't add the comma's at the end of the line:
String s = "[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]";
for (String l: s.split("\\]\\s*,\\s*\\[")) {
l = l.replaceAll("\\[", "").replaceAll("\\]", "");
System.out.println("{" + l + "}");
}
Assuming that the input string will always be in that format, with 4 integers between each bracket, I think the best way to do it would simply be to use a Scanner object and it's nextInt() method which will ignore the brackets and comma's and just find the numbers. Then put them into a 2d array like how you would with a loop.
It kinda gets rid of all the fun you were having with removing the brackets though, so it's not really better in terms of making an exercise out of this.

How to Find Missing Number on Integer Array of 1 to 100?

Here is what i did. What can i do further? Can anybody suggest? I am looking for bitset solution.
public static void main(String args[]) {
// one missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6}, 6);
// two missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6, 7, 9, 8, 10}, 10);
// three missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6, 9, 8}, 10);
// four missing number
printMissingNumber(new int[]{1, 2, 3, 4, 9, 8}, 10);
// Only one missing number in array
int[] iArray = new int[]{1, 2, 3, 5};
int missing = getMissingNumber(iArray, 5);
System.out.printf("Missing number in array %s is %d %n",
Arrays.toString(iArray), missing);
}
For n sequential numbers, the sum s = n(n+1)/2.
Sum up the numbers in the array and subtract it from s to find the missing number.
If n is the largest number, and there is only one missing, then the missing number is
n * (n + 1) / 2 - sum{elements in your array}
The first term is the sum of n consecutive integers from 1 to, and including, n.

Large arraylist, finding the product of certain amount of elements

I have an array list which contains the numbers below, and what i am trying to do is find the product of every 16 numbers.
try {
for (int z = 0; z < 1000; z++) {
System.out.println(list.subList(z, z + 16));
the above prints this
[7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2]
[3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4]
[1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9]
[6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1]
etc......
my solution was to put every line above in to an array and find the product of that array.However i am stuck, was wondieering if anyone can provide me a few pointers on about how to take a hit at this
list.subList(z, z + 16);
for(int i = 0; i < list.subList(z, z+16).size();i++){
Ar[i] = list.get(z);
}
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
If you had a ArrayList of ArrayList then you could do
ArrayList <ArrayList> listofList = new ArrayList ();
for (int z = 0; z < 1000; z = z + 16) {
int endpoint = z + 16; // check to see not bigger than 1000
ArrayList thisList = list.subList(z, endpoint);
listOfList.add (thisList);
System.out.println(thisList);
}
But there again you may want to just add up as you go.
ArrayList thisList = list.subList(z, endpoint);
int prod = 1;
for (int x : thisList) {
prod *= x;
}
If you look at the printout that you are showing, you will that it is just moving one number each time - not what you want.
This is the solution I came up with. Instead of printing out the answer, you coudl add it to an array or something and use it later. Fyi I subbed the zeroes for 1's so I knew it was working.
public static void main(String[] args) throws Exception
{
int[] arr = {7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 1, 6, 2, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 1, 6, 2, 4, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 1, 6, 2, 4, 9};
int counter = 0;
int product = 1;
for (int i : arr)
{
if (counter < 16)
{
product *= i;
counter++;
}
if (counter >= 16)
{
System.out.println(product);
product = 1;
counter = 0;
}
}
}
This is what printed (again I subbed the zeroes for ones):
60011280
34292160
102876480

Using specific numbers to reach a target number

For my assignment, I have to allow the player to select 6 numbers from two different lists as they please.
List<Integer> large = Arrays.asList(25, 50, 75, 100);
List<Integer> small = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10);
After they have selected their numbers say [100, 3, 5, 6, 9, 5] they then generate a target number of lets say for example 299 and they then can only use the numbers selected as a means of reaching the target using ONLY multiplication, addition, subtraction and division. So they could input for instance, 100 * 3 + 5 - 6 to reach the 299 target and this would be checked and scored appropriately.
Unfortunately I don't really have much to go on and I'm a bit confused on how to go about even starting to do that, I'm not looking for a straight up answer, maybe some pointers or external help would be much appreciated.
If we follow Bedmas (brackets exponents division multiplication addition subtraction) we can break this down into a simple function.
First turn the equation into a list of components:
100 * 3 + 5 - 6
changes to
["100", "*", "3", "+", "5", "-", "6"]
Now evaluate every element to make sure that they are valid. ie) Each value in the list of components must be in the selection list or have the value, */+-, Also if there are n nums, then there should be n-1 syms
To get the result we can then evaluate the list,.. merging num-sym-num sections as we go, in the order of bedmas
In pseudo:
func int compute_val(ListString eqn)
while not eqn.length is 1
if "*" in eqn
index = eqn.getIndex("*")
replace eqn[index -1:index +1] with str((int) eqn[index -1] * (int)eqn[index +1])
else if "/" in eqn
index = eqn.getIndex("/")
replace eqn[index -1:index +1] with str((int) eqn[index -1] / (int)eqn[index +1])
else if "+" in eqn
index = eqn.getIndex("+")
replace eqn[index -1:index +1] with str((int) eqn[index -1] + (int)eqn[index +1])
else if "-" in eqn
index = eqn.getIndex("-")
replace eqn[index -1:index +1] with str((int) eqn[index -1] - (int)eqn[index +1])
return (int)eqn[0]
This would be the progression of the list as the equation is evaluated in the loop
["100", "*", "3", "+", "5", "-", "6"] --> ["300", "+", "5", "-", "6"] -->
["305", "-", "6"] --> ["299"]
Is this helpful?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class JavaApplication97 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] s = {1, 2, 3, 4};
List<Integer> large = new ArrayList<>(Arrays.asList(25, 50, 75, 100));
List<Integer> small = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10));
List<Integer> yourNumbers = new ArrayList<>();
int numbersToSelect = 6;
while (numbersToSelect > 0) {
System.out.println("Choose " + numbersToSelect + " numbers from these numbers : " + large + " or " + small);
Integer input = in.nextInt();
boolean isItThere = false;
if (large.contains(input)) {
isItThere = true;
large.remove(input);
} else if (small.contains(input)) {
isItThere = true;
small.remove(input);
}
if (isItThere) {
yourNumbers.add(input);
numbersToSelect--;
System.out.println("Number " + input + " is added");
} else {
System.out.println("There is no such number");
}
}
}
}
Sample output :
Choose 6 numbers from these numbers : [25, 50, 75, 100] or [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
25
Number 25 is added
Choose 5 numbers from these numbers : [50, 75, 100] or [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
25
There is no such number
Choose 5 numbers from these numbers : [50, 75, 100] or [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
5
Number 5 is added
Choose 4 numbers from these numbers : [50, 75, 100] or [1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
5
Number 5 is added
Choose 3 numbers from these numbers : [50, 75, 100] or [1, 1, 2, 2, 3, 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
5
There is no such number
Choose 3 numbers from these numbers : [50, 75, 100] or [1, 1, 2, 2, 3, 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
100
Number 100 is added
Choose 2 numbers from these numbers : [50, 75] or [1, 1, 2, 2, 3, 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
6
Number 6 is added
Choose 1 numbers from these numbers : [50, 75] or [1, 1, 2, 2, 3, 3, 4, 4, 6, 7, 7, 8, 8, 9, 9, 10, 10]
50
Number 50 is added
You need multiple steps, and as I guess this is a homework task I'm not going to give a complete answer, however:
Parse the input string of the user
Calculate the result
Check if the result equals the target number
While 2 and 3 are trivial, the first part is probably the hardest for you and the core of the task. You can get more information on that task here: Smart design of a math parser?

Categories