How to interchange assignment of values in Java the most efficient way? - java

Say I have the following variables:
int x = 1;
int y = 2;
//some calculations follow(x and y stay the same init values) that somehow require you to interchange the values of y and x
how can I set y = 1 and x = 2 in one line of code??

Not sure why that's necessary, but you can do it like:
int x = 2, y = 1;

Try using bitwise XOR(^) operator.
x = x ^ y ^ (y = x);
Your completed code may look like,
class Main
{
public static void main (String[] args)
{
int x = 1, y = 2;
x = x ^ y ^ (y = x);
System.out.println("x after swapping:\nx="+x+"\ny after swapping,\ny="+y);
}
}

Related

Java program to swap two variables in single line?

We have discussed different approaches to swap two integers without the temporary variable. How would you swap variables in a single statement without using library function?
Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write “x, y = y, x”.
Pretty ugly, but this should do the trick..
int x = 100;
int y = 19;
x = y + -x + (y = x);
Outputs:
19,100
100,19
You can use bitwise xor
x = x ^ y ^ (y = x);
// Java program to swap two variables in single line
class GFG
{
   public static void main (String[] args)
   {
      int x = 5, y = 10;
      x = x ^ y ^ (y = x);
      System.out.println("After Swapping values of x and y are "
                          + x + " " + y);
   }
}

Subtraction (beginner)

public class Main {
public static void main (String[] args) {
int x = 0;
int y = 0;
while (x < 5) {
y = x - y;
System.out.print(x + y);
x = x + 1;
}
}
}
When I calculate this math myself. I get these answers:
y = 0 - 0 = 0
y = 1 - 0 = 1
y = 2 - 1 = 1
y = 3 - 1 = 2
y = 4 - 2 = 2
01122
But when I compile it. I get the answer
02356
I just don't get it. Could someone explain?
You are printing x+y not y
0+0=0 ; 1+1=2; 1+2=3; 2+3=5; 2+4=6
02356
In first iteration x=0,y=0 so x-y = 0 = y and x+y=0 so 0 will be printed.
In 2nd iteration x=1,y=0 so x-y = 1 = y and x+y=2 so 2 will be printed.
thus x and y will be updated.
In your calculation, you are not updating y
Use the debug, you will see that the iterations are correct because you are manipulating the x value after the x+y operation addition

Q: Headfirst Java for-loop exercise (Mixed Messages CH5)

I have been struggling with an exercise in the Java Headfirst book( CH5: p121 for reference). It's a loop inside another loop which adds/substracts some values from instance variables.
Input:
x = x + 3
Outputs:
x= 54 y = 6
public class MixFor5 {
public static void main(String[] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for (int inner = 4; inner > 1; inner--) {
x = x + 3;
y = y - 2;
if (x == 6) {
break;
}
x = x + 3;
}
y = y - 2;
}
System.out.println(x + " " + y);
}
}
My result is when doing it by myself with a notepad is x=42 y = 8 because then both loop conditions are met. What am i doing wrong? where did I go wrong in my thoughtprocess?
these are my notes -> pastebin note
I have not tried debugging first because I want to figure this by myself first so that I don't make the same mistakes in the future.
Thanks in advance,
tvanderv
if(x == 6) will never get true. The reason behind this is,
When inner = 4
x = x + 3 executes two times i.e. means x = 6.
then, inner = 3
now first x = x + 3 (before if(x == 3) condition) will give output x = 9. So x > 6 it will not break loop.
You did this step wrong in your notes.

Error while using Ternary operator with int and boolean

Can you please help me understand where i m doing the mistake.
I cam across this question while doing the beginner java material.
Ques: - Show how this sequence can be rewritten using the ? operator
if(x < 0) y = 10; else y = 20;
Ans: - x < 0 ? y =10 : y =20;
But when i tried performing the same i am getting an error
public class Ternary {
public static void main(String[] args) {
int result, x, y;
result = x < 0 ? y =10 : y =20;
System.out.println(result);
}
}
Error at result:- Multiple markers at this line
- Incompatible conditional operand types int and
boolean
- Syntax error on token "=", != expected
When you use a ternary operator you're assigning the left most variable to the result of the condition. In other words you only need two variables (I'll use result and x).
So the code should be:
result = x < 0 ? 10 : 20;
This will set result = 10 if x < 0 else result will be 20!
Replace the code like this. It will work.
public static void main(String[] args) {
int result, y;
int x = -1;
// Next try with int x = 1;
result = x < 0 ? (y = 10) : (y = 20);
System.out.println(result);
}

Java Recursion over 2 parameters and in two directions

I wish to recurse over two parameters simultaneously in a generic way. Here some explanation:
This is how the function calls should look like Func(int a, int b):
Call 0: Func(0, 0)
Call 1: Func(0, 1)
Call 1: Func(1, 0)
Call 1: Func(0, -1)
Call 1: Func(-1, 0)
How would I implement this in code, ensuring the following statements:
All possible combinations of a INRANGE (-INF, INF) and b INRANGE (-INF, INF) are considered.
There is no overhead, with that I mean that the same function is not used several times in the recursion.
I later want to expand it to do the same thing over 7 parameters.
Regards.
Here's my take on the spiral approach:
// this is your function
static void func(int x, int y)
{
System.out.println("x = "+x+", y = "+y);
}
// this calls func for all possible combinations of signs of the variables in arr
static void allPossibleSigns(int pos, Integer... arr)
{
if (pos == arr.length)
{
func(arr[0], arr[1]); // not really generic
}
else
{
allPossibleSigns(pos+1, arr);
arr[pos] = -arr[pos];
if (arr[pos] != 0)
allPossibleSigns(pos+1, arr);
}
}
static void caller()
{
for (int t = 0; t < MAX; t++)
for (int x = 0; x <= t; x++)
{
int y = (t-x);
allPossibleSigns(0, x, y);
}
}
If you want something more generic than func(arr[0], arr[1]);, you can replace it with:
Method[] methods = NewMain.class.getMethods();
for (Method m: methods)
{
if (m.getName().equals("func"))
m.invoke(null, arr);
}
and add some error checking. I used Integer... instead of int... in printAllPossibleSigns because of this approach (the above doesn't work for int...). This assumes you only have one function called func. If this is not the case, you'll have to add some additional checks.
For MAX = 4, it prints:
x = 0, y = 0
x = 0, y = 1
x = 0, y = -1
x = 1, y = 0
x = -1, y = 0
x = 0, y = 2
x = 0, y = -2
x = 1, y = 1
x = 1, y = -1
x = -1, y = -1
x = -1, y = 1
x = 2, y = 0
x = -2, y = 0
x = 0, y = 3
x = 0, y = -3
x = 1, y = 2
x = 1, y = -2
x = -1, y = -2
x = -1, y = 2
x = 2, y = 1
x = 2, y = -1
x = -2, y = -1
x = -2, y = 1
x = 3, y = 0
x = -3, y = 0
How this will be extended to 3 variable may not entirely be clear, so here's caller for 3 variables:
static void caller()
{
for (int t = 0; t < MAX; t++)
for (int x = 0; x <= t; x++)
for (int y = 0; y <= (t-x); y++)
{
int z = (t-x-y);
printAllPossibleSigns(0, x, y, z);
}
}
And that's about all you have to change, along with your function, obviously, and func(arr[0], arr[1]); if you didn't choose the generic approach.
I propose a spiral, non-recursively easiest.
For ease of reading the move is selected again in every step.
int x = 0;
int y = 0;
for (int t = 0; t < 100; ++t) {
func(x, y);
if (x <= 0 && y == 0) { // Widen spiral.
--x;
++y; // So next condition takes next.
} else if (x < 0 && y >= 0) { // Left, upper quadrant.
++x;
++y;
} else if (x >= 0 && y > 0) { // Right, upper.
++x;
--y;
} else if (x >= 0 && y <= 0) { // Right, lower.
--x;
--y;
} else if (x < 0 && y < 0) { // Left, lower.
--x;
++y;
} else {
throw new IllegalStateException("x = " + x + ", y = " + y);
}
}
I did not try the code! Check the conditions.
Maybe some knowledge of combinatorics would help here. To me this looks like you have a set of elements from -N to to +N. Now you want to call a function with for each variation of length == 7 those elements.
Such a range may be really big. Depending on the cost of the operation you want to call this might take longer than you live.
I would write an Iterator which delivers a new variation of the elements (which are your function parameters) on each call of next().
The implementation of such an iterator could you BigInteger, if you need big numbers. You could use an Array or List and change it's elements on each iteration. If you search for combinatorial algorithms or permutation / variation algorithms you might find details and maybe even implementations.
Another (similar) way (with more overhead, I think) would be to use just one number (e.g. a BigInteger) to mark the current variation. On each iteration you add 1 to this variation index number.
To get your parameters from this number you must perform a base transformation on this variation index. The base will be the number of elements in your elements set. The resulting number's digits each have the range of 0 to the number of elements -1. From this you can use each digit to get the parameters for your function call from the list of elements.
I did than some time ago and it works fine. Can't promise than I can find it.
For n dimensions:
Below I use positive numbers for coordinates. For every positive (greater 0) coordinate in a solution making the coordinate negative also is a solution (almost factor 2^n solutions more). (Using positive numbers simplifies the reading of a solution.)
This is a solutions for a coordinate vector of dimension n. The coordinates are chosen with ever growing "radius" = sum of coordinates.
static void func(int[] x) {
System.out.printf("%s%n", Arrays.toString(x));
}
/**
* Call many funcs with several coordinates.
* #param x n-dimensional coordinates.
* #param fromI starting index for variable coordinates.
* #param r radius, equal to the sum of x[>= fromIndex].
* #param t downward counter limiting the number of calls.
* #return new value of t.
*/
static int callFuncsForRadius(int[] x, int fromIndex, int r, int t) {
if (t <= 0) {
return t;
}
if (fromIndex >= x.length) { // Nothing more to vary.
if (r == 0) { // Read radius sum.
func(x);
--t;
}
return t;
}
for (int rNext = r; rNext >= 0; --rNext) {
x[fromIndex] = rNext;
t = callFuncsForRadius(x, fromIndex + 1, r - rNext, t);
if (t <= 0) {
break;
}
}
return t;
}
static int callFuncs(int[] x, int t) {
int r = 0;
while (t > 0) {
t = callFuncsForRadius(x, 0, r, t);
++r;
}
return t;
}
public static void main(String[] args) {
int n = 3;
int[] x = new int[n];
int t = 10; // N^n, where N = 2^31.
callFuncs(x, t);
}

Categories