/**
*
* @version \$Id: Ratio.java,v 1.1 1997/07/20 12:37:00 bailey Exp bailey \$
* @author duane a. bailey
*/

// modified 9/97 William Lenhart
// modified 2/98 Kim Bruce
// modified 2/99 Andrea Danyluk

import java.lang.Math;

public class Ratio
{ // an object for storing a fraction

protected int numerator; // numerator of ratio
protected int denominator; // denominator of ratio

public Ratio(int top, int bottom)
// pre: bottom != 0
// post: constructs a ratio equivalent to top/bottom
{
if (bottom < 0){
bottom = -bottom;
top = -top;
}
int reducer = gcd(bottom,top);
numerator = top/reducer;
denominator = bottom/reducer;
}

protected static int gcd(int first,int second)
// post: return gcd of first and second.
{
int fst,snd; // reduced versions of first, second
if ((first == 0) || (second == 0))
return 1;
else
fst = Math.abs(first);
snd = Math.abs(second);
int next = fst % snd; // indicates when done
while(next != 0){
fst = snd;
snd = next;
next = (fst % snd);
}
return snd;
}

public int getNumerator()
// post: return the numerator of the fraction
{
return numerator;
}

public int getDenominator()
// post: return the denominator of the fration
{
return denominator;
}

public boolean equals(Object other)
// post: returns true if the fractions are equal
// because all reduced, could be simpler.
{
Ratio otherRatio = (Ratio) other;
return (this.numerator * otherRatio.denominator) ==
(this.denominator * otherRatio.numerator);
}

// Should redefine hashcode, but ignore for now

public String toString()
// post: returns a string representation of the fraction
{
return numerator + "/" + denominator;
}

public double value()
// post: returns the real value equivalent to ratio
{
return (double)numerator/(double)denominator;
}

// pre: other is non-null
// post: return new fraction --- the sum of this and other
{
return new Ratio(this.numerator*other.denominator+
this.denominator*other.numerator,
this.denominator*other.denominator);
}

public static void main(String[] args)
{
Ratio r = new Ratio(1,1); // r == 1.0;
r = new Ratio(1,2); // r == 0.5;
r.add(new Ratio(1,3)); // r == 0.5;
r = r.add(new Ratio(1,4)); // r == 0.75

System.out.println(); // skip a line
System.out.println(r.value()); // 0.75 printed

Ratio q = new Ratio(9,12);
System.out.println("q = " + q);
System.out.println("r = " + r);
System.out.print("They are ");
if (!q.equals(r))
System.out.print("not ");
System.out.println("equal.");
System.out.println(); // skip a line
}
}