Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning Algorithms on myself, how do you implement tuples in java?

Tags:

java

algorithm

I'm teaching myself algorithms and I'm sorry if my title is incorrect! I don't 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 don't know how to implement the following parts in Java.

(q,r)=(0,0)
(q,r)=divide(⌊x/2⌋, y)
return (q,r)
like image 818
user3561871 Avatar asked Jan 22 '16 02:01

user3561871


2 Answers

Although Java lacks built-in support for tuples, good news is that you do not have to use tuples to implement this algorithm, except for the return value. Two regular int variables r and q will do.

// (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 tricky, because you have to return two values. Idiomatic way of doing it in Java is defining 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.

like image 89
Sergey Kalinichenko Avatar answered Nov 02 '22 10:11

Sergey Kalinichenko


You could use either an array or a class instance to contain and return more than one values. 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 a method :

return qrTuple;
like image 4
Manos Nikolaidis Avatar answered Nov 02 '22 08:11

Manos Nikolaidis