Learning algorithms on yourself, how do you implement tuples in java?

I teach myself algorithms and I'm sorry if my title is wrong! I do not understand how to implement this in Java.

if x = 0: return (q,r) = (0,0) (q, r) = divide(โŒŠx/2โŒ‹, y) q=2ยทq, r=2ยทr if x is odd: r=r+1 if rโ‰ฅy: r=rโˆ’y, q=q+1 return (q, r) 

I do not know how to implement the following parts in Java.

 (q,r)=(0,0) (q,r)=divide(โŒŠx/2โŒ‹, y) return (q,r) 
+6
source share
2 answers

Although Java does not have native tuple support, the good news is that you do not need to use tuples to implement this algorithm, except for the return value. Two ordinary variables int r and q will be executed.

 // (q,r)=(0,0) int q = 0, r = 0; // (q,r)=divide(โŒŠx/2โŒ‹, y) q = (x/2) / y; r = (x/2) % y; 

Returning is a bit complicated because you need to return two values. An idiomatic way to do this in Java is to define a class:

 class QandR { private final int q; private final int r; public QandR(int q, int r) { this.q = q; this.r = r; } } 

Now you can return new QandR(q, r) from your method.

+7
source

You can use an array or an instance of a class to contain and return more than one value. E.G.
(q,r) , where both q and r are of type int

 int[] qrTuple = new int[2]; // zero initialized 

or

 class QrTuple { int q, r; QR(int q, int r) { this.q = q; this.r = r; } } 

and then

 QrTuple qrTuple = new QrTuple(0, 0); 

in both cases you can do at the end of the method:

 return qrTuple; 
+4
source

All Articles