Check if number is in range of Dynamically Changing Numbers? - java

Is there a way to determine if a number is within a range of two specific numbers, if those numbers are changing? For example:
int num1 = -10;
int num2 = 100;
int num3 = 5;
if(num3 > num 1 && num3 < num2){
}
It would be rather easy to determine whether num3 is in between num1 and num2. However, lets say num1 and num2 change dynamically during the running of the program:
num2 becomes -30
All else remains the same. Now the same algorithm as before would no longer work. Is there an elegant way to check if a number is withing a range using dynamically changing max and min values?

You can try the following, i create 2 more variable iMin & iMax, and before checking num3 is in rank, we define max value and min value:
int num1 = -10;
int num2 = 100;
int num3 = 5;
if (num3 > Math.min(num1, num2) && num3 < Math.max(num1, num2)) {
}

That's kinda silly. If you have an algorithm in a function and you say you want num3 to be between num1 and num2, that's it. That rule shouldn't change, because num1 or num2 changed. The implementation should be generic and independent of the values.
If you need some verification prior to that, do it. I don't a see any other elegant way to do it.

Related

What is the time and space complexity of this code? I'm very confused on this subject so I am asking

This is my code, it is a russian peasant multiplication algorithm. I find the time and space complexity very confusing so I needed some help.
This is also for java language
Thank you.
int num1 = Integer.parseInt(jTextField1.getText());
int num2 = Integer.parseInt(jTextField2.getText());
int res=0;
// While second number doesn't become 1
while (num2 > 0)
{
// If second number becomes odd,
// add the first number to result
if ((num2 & 1) != 0)
res = res + num1;
// Double the first number
// and halve the second number
num1 = num1 << 1;
num2 = num2 >> 1;
}
jTextField3.setText(String.valueOf(res));
}
The loop continues to execute provided that num2 be greater than zero. After each iteration of the loop, num2 is halved. This means that the loop will execute log_2(num2) times. So, assuming num2 be represented by N, we can say that the complexity of this loop is log_2(N).

How can I add up two randomly generated numbers inclusively? Java

I'm asking the user to enter two random numbers(i.e 1 10) then I have to add them up inclusively, so (1 10) would be 55.
public int sum(int num1, int num2) {
int counter; //just a variable until I clean this up and get it to work
questions++;
if (num1 < num2) {
int difference = num2-num1;//difference between the given numbers
int holder = 0;
while (holder <= difference) {
holder ++;
num1 += num1;
}
counter = num1;
}
}
This is the chunk of code I have been testing. This gives me 256 when I run 1 and 10.
if (num1 < num2)
{
int answer = num1;
while (num1 <= num2)
{
answer = answer + num1++;
}
retrun answer;
}
Java 8 variant:
IntStream.rangeClosed(Math.min(num1, num2), Math.max(num2, num1)).sum()
What it does:
Create range of ints that contains all numbers from num1 to num2 inclusively
we need to make sure that left border always less than right one, otherwise range will be empty. That's why I've used min() and max()
Add all the numbers together.
Beware though:
Certain combinations of numbers produce a sum that's higher than Integer.MAX_VALUE, and this will cause the sum to overflow and possibly produce negative values.
This can be accounted for by using slightly different version, that's slightly less performant:
IntStream.rangeClosed(Math.min(num1, num2), Math.max(num2, num1))
.mapToObj(BigInteger::valueOf)
.reduce(BigInteger.ZERO, BigInteger::add);
public int sum(int num1, int num2) {
int result = 0;
while(num1<=num2) {
System.out.println("num1 is: "+num1);
result = result + num1;
num1++;
}
return result;
}
Please note the print line within the loop to display the progress of the while.
I'm guessing you're doing this as a programming exercise, so using a loop is the whole point of the task. However, if you just wanted code that gave you the right answer you could use the arithmetic series formula:
public int sum(int num1, int num2) {
if (num1 <= num2) {
return (num2 - num1 + 1) * (num1 + num2) / 2;
}
return 0;
}

How do I use increment in calculations?

{int num1 = 5;
int num2 = 6;
int num3;
num3 = ++num2 * num1 / num2 + num2;
System.out.println(num3);} //12
The compiler gives the num3 = 12, but how do I get that value? when I try to get that num3 value I got 6(by without using compiler). Both value of num2++ and ++num2 gives the same, but when I use following code it gives a different value. Why I got different values. what are the steps for get those num3 values (without using compiler?)
num3 = num2++ * num1 / num2 + num2; //11
Both increment operation num++ and ++num will result into num=num+1 there is only difference between the order of assignment and increment operations.
num++(post-increment) -> first num is used and then incremented
++num(pre-increment) -> first num is incremented and then used
You code prints 12 when I tested.
public static void main(String[] args) {
int num1 = 5;
int num2 = 6;
int num3;
num3 = ++num2 * num1 / num2 + num2;
System.out.println(num3);
}
I will suggest you to make use of brackets as it will increase readability as well.
If you do:
int num2 = 6;
System.out.println(num2++);
It will print 6, and then change num2 to 7. But if you do:
int num2 = 6;
System.out.println(++num2);
It will change num2 to 7 and then print 7. So:
num3 = ++num2 * num1 / num2 + num2;
num3 = 7 * 5/ 7 + 7
num3 = 35/7 + 7
num3 = 12

How to input different numbers with Java

The question is to Write a program that sorts three integers. The integers are entered from the input dialogs and stored in variables num1, num2, and num3, respectively. The program sorts the numbers so that num1 <= num2 <= num3.
actually I do that but the result is available only to 1 ,2 and 3 numbers !
When I enter any different number it doesn't show me the result I want it !
here is my code..
import javax.swing.JOptionPane;
public class number order {
public static void main(String[] args) {
int num1;
int num2;
int num3;
String n = JOptionPane.showInputDialog(null, "input NUM 1 " );
num1 = Integer.parseInt(n);
String u = JOptionPane.showInputDialog(null, "input NUM 2 " );
num2 = Integer.parseInt(u);
String m = JOptionPane.showInputDialog(null, "input NUM 3 " );
num3 = Integer.parseInt(m);
if (num1<=num2&& num2<=num3)
System.out.println( num1+"<="+ num2+"<="+num3 );
if(num2<=num1&&num1<=num3)
System.out.println(num2+"<="+num1+"<="+num3);
if (num3<=num1&&num1<=num2)
System.out.println(num3+"<="+num1+"<="+num2);
// TODO code application logic here
}
}
The problem is that you check only three out of six possible arrangements of those three numbers. Also note that, even for those three, you are not actually sorting the numbers, but only printing them in sorted order, i.e., you are never reassigning the variables num1, num2, and num3.
Just as an alternative to checking all the possible arrangements of the three numbers or implementing a full sorting algorithm, you can also compare and swap pairs of numbers. This way, you get away with far fewer comparisons while still being able to sort all permutations of three numbers.
if num1 > num2, swap num1 and num2
if num2 > num3, swap num2 and num3
if num1 > num2, swap num1 and num2 again
After those three swaps, the numbers are in sorted order.
Of course, if you have more than three numbers this gets impractical, and you should rather implement a full sorting algorithm (for exercise) or go with one of the builtins, like Arrays.sort (for real life).
You haven't checked all cases:
1 < 2 < 3
1 < 3 < 2
2 < 1 < 3
2 < 3 < 1
3 < 1 < 2
3 < 2 < 1
However to check all case like that is not to useful.
an sorted array would be more easy:
int arr[3]={num1,num2,num3}
java.utils.Arrays.sort(arr);
println(arr[0] + "<=" + arr[1] + "<=" + arr[2]);
int[] all = new int[]();
num1 = Integer.parseInt(n);
all[0] = num1;
num2 = Integer.parseInt(u);
all[1] = num1;
num3 = Integer.parseInt(m);
all[2] = num1;
for(int i=0; i <all.length ;i++){
if(i!=0 && all[i]< all[i-1]){
temp = all[i-1];
all[i-1] = all[i];
all[i] = temp;
}
}
all will have sorted array
or more simply
2 steps
1)add all to a array.
2) call Arrays.sort(array)
how about
int min = min(min(num1,num2),num3);
int max = max(max(num1,num2),num3);
int mid = num1 + num2 + num3 - min - max;
System.out.println(min+"<="+mid+"<="+max);
if(num1 < num2){ if(num3 < num1) System.out.println("num2 > num1 > num3");}
else{ if(num2 < num3) System.out.println("num3 > num2 > num1"); else System.out.println("num1 > num2 > num3");}
Sort in descending order.
Hope it helps.

user defined size of a two dimensional array (Java)

I'm new to java, and i'm trying to make a array who's size is user defined. I'm staring off by filling in the entire array with zeros and moving from there. How should I go about doing that? What I have right now is something similar to: (input being my scanner object)
int num1, num2, num3 = 0, num4 = 0, active = 0;
num1 = input.nextInt();
num2 = input.nextInt();
int[][] ver = new int[num1][num2];
while(active == 0){
ver [num3][num4] = 0;
++num4;
if(num4 > num2){
++num3;
num4 = 0;
}
if(num3 > num1){
++active
}
}
This keeps giving me an ArrayIndexOutOfBoundsException:0, making me think ver[0][0] doesn't exist. Thanks in advance.
You are not checking num3 and num4 properly (they both are allowed to reach the upper bound) so they will eventually go out of bounds.
Since you're just trying to fill your array with zeros why don't you consider the following code:
import java.util.Arrays;
// ...
int num1 = 2; // fixed number just for test purposes
int num2 = 2; // fixed number just for test purposes
int[][] ver = new int[num1][num2];
for (int[] row: ver)
Arrays.fill(row, 0);
System.out.println(ver[0][0]); // prints 0 as expected
Since every subarray (row in the example) is an array the above code will loop through them filling them with zeros, taking advantage of the fill method of the Arrays class, which you need to import as shown in the example.
There is no checking for the values of num3 and num4 in your code. Add proper restrictions as I envisage, you don't what them to be greater thatn num1 and num2 respectively.
If the value of num3 or num4 goes beyond the limit you get the ArrayIndexOutOfBoundException.
This fails when num4 == num2 as you are checking num4 > num2; because num2 is the length of the array while index goes to length-1. Same goes with num3 and num1 comparison. Use num2-1 and num1-1 in the comparison as below:
int num1=0, num2=0, num3=0,num4=0;
num1 = input.nextInt(); //<--Input a value >0
num2 = input.nextInt(); //<--Input a value >0
int[][] ver = new int[num1][num2];
int active = 0;
while(active == 0){
ver[num3][num4] = 0;
++num4;
if(num4 > num2-1){ // or if(num4 >= num2)
++num3;
num4 = 0;
}
if(num3 > num1-1){ // or if(num3 >= num1)
++active;
}
}

Categories

Resources