Java: How to generate a random number bigger than x, no maximum? - java

I just want to generate a random number bigger than x, without a maximum value, to operate with it afterwards. I've been searching for answers to my question but none of them match my problem: they refer to a restriction with minimum and maximum values. I want a simple code just like:
Random number = new Random();
int x = 0; //the minimum value
int finalNumber;//any positive random number, in this case; if, for example, x were 2, some number bigger than 2.
How can I get finalNumber?
Thanks for taking your time in posting an answer, I would really appreciate it.

Since information is stored into finite bytes you can't in any case generate a number with "no maximum".
So assuming your limit it Integer.MAX_VALUE then you can generate a number in [0, Integer.MAX_VALUE - minimum] and then add minimum to the result.
Eg:
final int MINIMUM = ...
int v = random.nextInt(Integer.MAX_VALUE - MINIMUM) + MINIMUM;
Mind that this is exclusive since nextInt(int) contract specify that upper bound is excluded. And that this required MINIMUM to be positive.

Try this:
if (x > 0) {
return (int)(Math.random() * (Integer.MAX_VALUE - x)) + x;
}

Why not just wrap it with your own class/utility method say MyMath.Random() like this method:
public class MyMath{
public static int Random()
{
final int MIN = 0;
final int MAX = Integer.MAX_VALUE;
return (int)(Math.random() * MAX);
}
/// overload so you can specify min value
public static int Random(in MIN)
{
final int MAX = Integer.MAX_VALUE;
return (int)(Math.random() * (MAX-MIN));
}
}
You can refer to the Integer.MAX_VALUE from the Java docs here
This way you can just do:
int someInt = MyMath.Random();
or
int x = 123;
int someInt = MyMath.Random(x);

Related

Rounding integers to one significant digit

I want to round down an int in Java, what i mean is, if I have an int 45678, i want to convert that int into 40000
this is how im calling it
int den = placeValue(startCode,length);
and this is the code
static int placeValue(int N, int num)
{
int total = 1, value = 0, rem = 0;
while (true) {
rem = N % 10;
N = N / 10;
if (rem == num) {
value = total * rem;
break;
}
total = total * 10;
}
return value;
}
so if i have 89765, i would want 80000,
but instead it return the place value of whatever length is.
So,
for 89765, the length would be 5, so the return value is 5 i.e. the value in the ones place.
but if the number was 85760
then it would return 5000.
I hope that makes sense.
Any suggestions would be much appreicated.
In my opinions, if I can avoid 'calculating' I will compute the answer from other concept since I am not confidence on my math (haha).
Here is my answer. (only work in positive numbers)
I think the length of the inputted number is not necessary.
static int placeValue2(int N) {
String tar = N+"";
String rtn = tar.substring(0,1); // take first digital
for (int i=0;i<tar.length()-1;i++) // pad following digitals
rtn+="0";
return Integer.parseInt(rtn);
}
I appreciate you asked the question here.
Here is my solution. I don't know why you are taking two parameters, but I tried it from one param.
class PlaceValue{
int placeValue(int num){
int length = 0; int temp2=1;
boolean result=false;
long temp1=1;
if (num<0){
result=true;
num=num*(-1);
}
if (num==0){
System.out.println("Value 0 not allowed");
return 0;
}
while (temp1 <= num){ //This loop checks for the length, multiplying temp1 with 10
//untill its <= number. length++ counts the length.
length++;
temp1*=10;
}
for (int i=1; i<length; i++){//this loop multiplies temp2 with 10 length number times.
// like if length 2 then 100. if 5 then 10000
temp2=temp2*10;
}
temp2=(num/temp2)*temp2;
/* Let's say number is 2345. This would divide it over 1000, giving us 2;
in the same line multiplying it with the temp2 which is same 1000 resulting 2000.
now 2345 became 2000;
*/
if (result==true){
temp2=temp2*(-1);
}
return temp2;
}
}
Here is the code above. You can try this. If you are dealing with the long numbers, go for long in function type as well as the variable being returned and in the main function. I hope you understand. otherwise, ask me.
Do you want something like this?
public static int roundDown(int number, int magnitude) {
int mag = (int) Math.pow(10, magnitude);
return (number / mag) * mag;
}
roundDown(53278,4) -> 50000
roundDown(46287,3) -> 46000
roundDown(65478,2) -> 65400
roundDown(43298,1) -> 43290
roundDown(43278,0) -> 43278
So the equivalent that will only use the most significant digit is:
public static int roundDown(int number) {
int zeros = (int) Math.log10(number);
int mag = (int) Math.pow(10, zeros);
return (number / mag) * mag;
}

How to generate a certain amount of random numbers within a range in Java?

I'm trying to make a small program that allows you to generate a certain amount of numbers within a range, but it does not work as expected.
For example, if I ask the program to generate 3 random numbers between 5 and 10 it gives me 5 random numbers between 0 and 5.
private void jFillActionPerformed(java.awt.event.ActionEvent evt) {
int intInput1;
int intInput2;
int intInput3;
int i;
int RandomNumber;
intInput1 = Integer.parseInt(txtInput1.getText());
intInput2 = Integer.parseInt(txtInput2.getText());
intInput3 = Integer.parseInt(txtInput3.getText());
int ListSize = (intInput3) + 1;
Random rnd = new Random();
for (i = 0; i <= ListSize; i++)
{
RandomNumber = rnd.nextInt((intInput2 - intInput1) + 1);
fill.addElement(RandomNumber);
lstNumbers.setModel(fill);
}
Simply always add 5 (or more specifically - intInput1 in your case as it seems it's lower range value) to generated numbers so it will be in the range you need (0+5=5, 5+5=10 so it will be in range 5,10)
Here an IntStream you can later than use limit to set the amount of numbers you want.
public static IntStream numbersBetween(int from, int to){
return new Random().ints().map(e -> Math.abs(e % ((to+1) - from)) + from);
}

searching for the highest and the smallest value in a specific range - Random

so far in the program the values were searched randomly, but I want to modify the program to search for random numbers in a given range. Generally speaking, My point is that the draw should be from the given range (from-to), and not up to 1000 random numbers as in the above code, so my question is:
How can I pass the value from and to random: rand.nextInt (?) so that the numbers are randomly drawn in a given range. so I generally need to get a printout from the program like in the question: expected output
// Create array to be searched
final int[] arrayToSearch = new int[20];
Random rnd = new Random();
for (int i = 0; i < arrayToSearch.length; i++)
arrayToSearch[i] = rnd.nextInt(1000);
System.out.println(Arrays.toString(arrayToSearch));
final int PARTITIONS = 4;
Thread[] threads = new Thread[PARTITIONS];
final int[] partitionMin = new int[PARTITIONS];
final int[] partitionMax = new int[PARTITIONS];
for (int i = 0; i < PARTITIONS; i++) {
final int partition = i;
threads[i] = new Thread(new Runnable() {
#Override
public void run() {
// Find min/max values in sub-array
int from = arrayToSearch.length * partition / PARTITIONS;
int to = arrayToSearch.length * (partition + 1) / PARTITIONS;
int min = Integer.MAX_VALUE,
max = Integer.MIN_VALUE;
for (int j = from; j < to; j++) {
min = Math.min(min, arrayToSearch[j]);
max = Math.max(max, arrayToSearch[j]);
}
partitionMin[partition] = min;
partitionMax[partition] = max;
});
so far:
partition 0: from=0, to=5, min=23, max=662 //the draw in the range 0-5, draw is outside the specified range
expected output:
partition 1: from=0, to=5, min=1, max=3 // the draw takes place within the given range 0 to 5
partition 2: from=20, to=30, min=22, max=29 //the draw takes place within the given range 20 to 30
How can I pass the value from and to random: rand.nextInt (?) so that the numbers are randomly drawn in a given range
Try it like this. This will generate values between from and to inclusive.
int from = -100;
int to = 100;
int draw = ThreadLocalRandom.current().nextInt(from, to);
You can actually generate your own Supplier to just get random numbers in a specified range.
The BiFunction returns a Supplier. And the Supplier can be called to get the a random number in the range.
BiFunction<Integer, Integer, IntSupplier> rndGen = (f,
t) -> () -> ThreadLocalRandom.current().nextInt(f, t+1);
IntSupplier rnd = rndGen.apply(from,to);
So each time rnd.getAsInt() is invoked, you will get a number in the desired range.
Note: There are of course methods that do this pretty much automatically. But I presumed you wanted to work out the logic of finding min and max yourself so I did not include those.
Class Random has method ints (long streamSize, int randomNumberOrigin, int randomNumberBound) to generate IntStream of random numbers in the given range, and then the summary statistics may be collected for such stream:
static void printMinMax(int size, int from, int to) {
IntSummaryStatistics stats = new Random()
.ints(size, from, to)
.summaryStatistics();
System.out.printf("min = %d, max = %d%n", stats.getMin(), stats.getMax());
}
Test:
printMinMax(20, 20, 200); // min = 30, max = 198
Create a random number of your choosing however you want.
If it's under your From value, add your From value to it.
If it's over your To value mod it by your To value.

C(n,r) calculator program doesn't work

I made a C(n,r) calculator using java Netbeans JFrameform.
here is the frame
Here is the code :-
private void lllActionPerformed(java.awt.event.ActionEvent evt) {
int n=Integer.parseInt(t1.getText());
int r=Integer.parseInt(t2.getText());
int s=1;
for(int i=1;i<=n;i=i+1){
s=i*s;
}
int p=1;
for(int j=1;j<=n-r;j=j+1){
p=j*p;
}
int q=1;
for(int k=1;k<=r;k=k+1){
q=k*q;
}
int re=s/(p*q);
t3.setText(" "+re);
}
the code works well for values values of n upto 12. But for 13 and onward , code starts giving wrong answer.
wrong output
why is this happening? Your help is appreciated.
During the calculations the value goes over Integer.MAX_VALUE This is an overflow of arithmetic operation:
Integer overflow can be demonstrated through an odometer overflowing, a mechanical version of the phenomenon. All digits are set to the maximum 9 and the next increment of the white digit causes a cascade of carry-over additions setting all digits to 0, but there is no higher digit to change to a 1, so the counter resets to zero. This is wrapping in contrast to saturating.
In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.
Try to replace int with long values. It will work with a greater value.
private void lllActionPerformed(java.awt.event.ActionEvent evt) {
int n=Integer.parseInt(t1.getText());
int r=Integer.parseInt(t2.getText());
int s=1;
for(int i=1;i<=n;i=i+1){
s=i*s;
}
long p=1L;
for(int j=1;j<=n-r;j=j+1){
p=j*p;
}
long q=1L;
for(int k=1;k<=r;k=k+1){
q=k*q;
}
long re=s/(p*q);
t3.setText(" "+re);
}
With 14 and 2 as inputs the result is 91.
If you want to have a correct result for big values you have to use a BigInteger that handle:
Immutable arbitrary-precision integers
Try using this
private void lllActionPerformed(java.awt.event.ActionEvent evt) {
int n=Integer.parseInt(t1.getText());
int r=Integer.parseInt(t2.getText());
if (r > n / 2) r = n - r; // because C(n, r) == C(n, n - r)
long ans = 1;
int i;
for (i = 1; i <= r; i++) {
ans *= n - r + i;
ans /= i;
}
t3.setText(" "+ans);
}

decimal to binary conversion java

My method seems to only work for all int less than 2^10. If it is greater than or equal to this value then it just returns 2^32. I'm not sure how my program is even getting this. I need to make it work for all int less than or equal to 2^15. Can anybody at least see why it's returning 2^32 for int greater than or equal to 2^10? If so then let me know please.
public static int DecToBin(int num) {
int binNum = 0;
int divisor = num;
int mod = 0;
int exp =0;
while(divisor != 0){
mod = divisor%2;
divisor = divisor/2;
if(mod==1){
binNum = (int) (binNum + (Math.pow(10, exp)));
}
exp++;
}
return binNum;
}
An always easy way to accomplish this is:
Integer.toBinaryString(int);
This is the easiest way to do this but their might be more efficiant ways to do it.
Hopefully this is what you were looking for
As Taco pointed out, you can call Integer.toBinaryString(int), but if this is for an assignment or something where you should write the method yourself, here is what I would do.
I would write a method, that will constantly divide the number by 2, and store the remainders in a String. Something like this:
String binaryString = "";
int value = 100;
while(value > 0){
int remainder = value % 2;
value = value/2;
binaryString = remainder + binaryString;
}
I tested this in a quick console run and it produced '1100100' which is correct.
EDIT I used this as a reference.

Categories

Resources