Java Random Fraction within Range - java

How can i Generate an array with 10 random fractions between 10/1 and 1/10 . i have coded java class Rational to do this work .
inside Rational Class , there are some basic methods are defined . please have a look on the class .
public class Rational {
// Private instance variables
private int numerator;
private int denominator;
// Constructor
public Rational(){
this.numerator = 0;
this.denominator = 1;
}
// Overloaded constructor
public Rational(int num, int den){
this.numerator = num;
this.denominator = den;
reduce();
}
// Getter method for numerator
public int getNumerator(){
return this.numerator;
}
// Getter method for denominator
public int getDenominator(){
return this.denominator;
}
// Getter method for double
public double toDouble(){
return(double)this.numerator/this.denominator;
}
// Getter method for string
public String toString(){
if(denominator == 0){
return "ERROR";
}
if(denominator == 1){
return this.numerator + "";
}
else {
return this.numerator + "/" + this.denominator;
}
}
// Void method for negate
public void negate(){
this.numerator = -1 * numerator;
}
// Void method for invert
public void invert(){
int flip = this.numerator;
this.numerator = this.denominator;
this.denominator = flip;
}
// Value method for addition
public Rational add(Rational test){
this.numerator = (numerator * denominator) + (test.getDenominator() * test.getNumerator());
this.denominator = test.getDenominator() * denominator;
return new Rational(numerator,denominator);
}
// Euclid's GCD
private static int gcd(int x, int y){
if (0 == y){
return x;
}
else {
return gcd(y,x%y);
}
}
// Void method for reduce, using GCD
public void reduce(){
int div;
div = Rational.gcd(numerator, denominator);
this.numerator = numerator/div;
this.denominator = denominator/div;
}
// *Bonus* value method for multiplication
public Rational multiply(Rational test){
int numx = this.numerator * test.getNumerator();
int denx = this.denominator * test.getDenominator();
return new Rational(numx, denx);
}
}
But i am having problem in creating that logic to generate random fraction with that specific range ...

You can follow this simple strategy. You know that your fraction is between 1/10 and 10, which means,
1/10 < num/den < 10 ...(1)
Which implies that,
den/10 < num < 10*den ...(2)
So, first randomly fix the den (choose randomly from 0 to 9). Once you have fixed this, randomly choose a number from the range den/10 to 10*den

Related

Using two methods in a class (Rational) to simplify a fraction

I have a class definition for a class of rational numbers. My assignment is to be able to add, multiply and divide any fraction I put in my main function. My program can do all that, but I'm having trouble simplifying the fractions. I want to try and use only two methods to simplify, for example public void reduce(); and private static gcd();
public class Rational {
private int num;
private int denom;
public Rational() {
num = 0;
denom = 1;
}
public Rational(int n, int d) {
num = n;
denom = d;
reduce();
}
public Rational plus(Rational t) {
int tnum = 0;
int tdenom = 1;
tnum = (this.num * t.denom) + (this.denom * t.num);
tdenom = (t.denom * this.denom);
Rational r = new Rational (tnum, tdenom);
return r;
}
public Rational minus(Rational t) {
int tnum = 0;
int tdenom = 1;
tnum = (this.num * t.denom) - (this.denom * t.num);
tdenom = (t.denom * this.denom);
Rational r = new Rational (tnum, tdenom);
return r;
}
public Rational multiply(Rational t) {
int tnum = 0;
int tdenom = 1;
tnum = this.num * t.num;
tdenom = t.denom * this.denom;
Rational r = new Rational (tnum, tdenom);
return r;
}
public Rational divide(Rational t) {
int tnum = 0;
int tdenom = 1;
tnum = this.num / t.num;
tdenom = this.denom / t.denom;
Rational r = new Rational (tnum, tdenom);
return r;
}
private static int gcd(int n, int d) {
return gcd(d, n%d);
}
public void reduce() {
//call gcd
gcd(num, denom);
//divide num and denom by gcd by
num = num / gcd(num,denom);
denom = denom / gcd(num,denom);
}
public String toString() {
return String.format("%d/%d", num, denom);
}
}
public class RationalMain {
public static void main(String[] args) {
Rational x = new Rational();
Rational y = new Rational(1,4);
Rational z = new Rational(1,2);
//x = y - z;
x = y.plus(z);
System.out.printf("%s = %s + %s\n", x.toString(), y.toString(), z.toString());
x = z.minus(y);
System.out.printf("%s = %s - %s\n", x.toString(), z.toString(), y.toString());
x = z.multiply(y);
System.out.printf("%s = %s * %s\n", x.toString(), z.toString(), y.toString());
x = y.divide(z);
System.out.printf("%s = %s / %s\n", x.toString(), y.toString(), z.toString());
}
}
That's not how you might achieve the Greatest Common Divisor (GCD). Before you will be able to get your code to work properly you will need to at least fix your gcd() method since currently it will recurse until an ArithmeticException (/ by zero) is generated. You might achieve the task this way:
private static int gcd(int num, int den) {
num = Math.abs(num); // if numerator is signed convert to unsigned.
int gcd = Math.abs(den); // if denominator is signed convert to unsigned.
int temp = num % gcd;
while (temp > 0) {
num = gcd;
gcd = temp;
temp = num % gcd;
}
return gcd;
}
To convert your fractions too their Lowest Terms your reduce() method might look like this if it accepted a Fraction String as an argument (you modify the method parameters if you like):
/*
A Fraction String can be supplied as: "1/2", or "2 1/2", or
"2-1/2, or "-2 32/64", or "-2-32/64". The last 2 examples are
negative fraction values.
*/
private String reduce(String fractionString) {
// Fraction can be supplied as: "1/2", or "2 1/2", or "2-1/2".
// Make sure it's a Fraction String that was supplied as argument...
inputString = inputString.replaceAll("\\s+", " ").trim();
if (!inputString.matches("\\d+\\/\\d+|\\d+\\s+\\d+\\/\\d+|\\d+\\-\\d+\\/\\d+")) {
return null;
}
str2 = new StringBuilder();
String wholeNumber, actualFraction;
if (inputString.contains(" ")) {
wholeNumber = inputString.substring(0, inputString.indexOf(" "));
actualFraction = inputString.substring(inputString.indexOf(" ") + 1);
str2.append(wholeNumber);
str2.append(" ");
}
else if (inputString.contains("-")) {
wholeNumber = inputString.substring(0, inputString.indexOf("-"));
actualFraction = inputString.substring(inputString.indexOf("-") + 1);
str2.append(wholeNumber);
str2.append("-");
}
else {
actualFraction = inputString;
}
String[] tfltParts = actualFraction.split("\\/");
int tfltNumerator = Integer.parseInt(tfltParts[0]);
int tfltDenominator = Integer.parseInt(tfltParts[1]);
// find the larger of the numerator and denominator
int tfltN = tfltNumerator;
int tfltD = tfltDenominator;
int tfltLargest;
if (tfltNumerator < 0) {
tfltN = -tfltNumerator;
}
if (tfltN > tfltD) {
tfltLargest = tfltN;
}
else {
tfltLargest = tfltD;
}
// Find the largest number that divides the numerator and
// denominator evenly
int tfltGCD = 0;
for (int tlftI = tfltLargest; tlftI >= 2; tlftI--) {
if (tfltNumerator % tlftI == 0 && tfltDenominator % tlftI == 0) {
tfltGCD = tlftI;
break;
}
}
// Divide the largest common denominator out of numerator, denominator
if (tfltGCD != 0) {
tfltNumerator /= tfltGCD;
tfltDenominator /= tfltGCD;
}
str2.append(String.valueOf(tfltNumerator)).append("/").append(String.valueOf(tfltDenominator));
return str2.toString();
}
As you can see, a whole number can also be supplied with your fraction so, if you do a call to the above reduce() method like this:
System.out.println(reduce("12-32/64"));
System.out.println(reduce("12 32/64"));
The console window will display:
12-1/2
12 1/2

please explain how to implement main method in my code?

Please explain how to implement main method. i am having trouble with the main method and the line after main method, why the line after main method showing illegal start of expression?? is it because i forgot to put bracket somewhere or my code is wrong?? the code is suppose to perform arithmetic with fraction.
public class Rational{
public static void main(String [] args){
public int numerator;
public int denominator;
public Rational(int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
reduce();
}
public Rational add(Rational other)
{
int num = numerator * other.denominator + other.numerator * denominator;
int den = denominator * other.denominator;
return new Rational(num, den);
}
public Rational subtract(Rational other)
{
int num = numerator * other.denominator - other.numerator * denominator;
int den = denominator * other.denominator;
return new Rational(num, den);
}
public Rational multiply(Rational other)
{
int num = numerator * other.numerator;
int den = denominator * other.denominator;
return new Rational(num, den);
}
public Rational divide(Rational other)
{
int num = numerator * other.denominator;
int den = denominator * other.numerator;
return new Rational(num, den);
}
private void reduce()
{
int min = 0;
if(numerator > denominator)
{
min = denominator;
}
else
{
min = numerator;
}
for(int i = min; i > 1; i--)
{
boolean isNumDiv = numerator % i == 0;
boolean isDenDiv = denominator % i == 0;
if(isNumDiv && isDenDiv)
{
numerator = numerator / i;
denominator = denominator / i;
break;
}
}
}
public String toString()
{
return numerator + " / " + denominator;
}
} }
Suppose you have to create a program that prints a sum. You can create a file Sum.java with the Sum class inside it. Like this:
public class Sum {
public int x;
public int y;
public Sum(int x, int y) {
this.x = x;
this.y = y;
}
public int sumMyNumbers() {
return x + y;
}
}
Now you can create a file named Main.java with your Main class that will be the entry point of your program and it could be like this:
public class Main {
public static void main(String[] args) {
// It will print the number 4 on your console
System.out.println(new Sum(2, 2).sumMyNumbers());
// Or like this:
Sum mySum = new Sum(2,2);
System.out.println(mySum.sumMyNumbers());
// Or even like this:
int i = new Sum(2, 2).sumMyNumbers();
System.out.println(i);
}
}
So your first mistake is that you are putting everything inside your main method.

Why isn't the sort method working?

I have to sort an array of fractions here is my code for the class which is working fine.
public class Fraction implements Comparable<Fraction>{
private int numerator;
private int denominator;
public Fraction(int num, int den){
numerator = num;
denominator = den;
}
public int compareTo(Fraction fraction){
if(decimalValue()>fraction.decimalValue()){
return 1;
}else if(decimalValue()<fraction.decimalValue()){
return -1;
}else{
return 0;
}
}
public Fraction reduce(int numerator, int denominator){
if(numerator==0&&denominator==0){
numerator = 0;
denominator = 0;
}
else{
for(int x = Math.min(Math.abs(numerator), Math.abs(denominator)); x>0; x--){
if(denominator == numerator){
numerator = 1;
denominator = 1;
}
else if(numerator == 0){
numerator = 0;
denominator = 1;
}
else if(numerator%x==0 && denominator%x==0){
numerator = numerator/x;
denominator = denominator/x;
}
}
}
public double decimalValue(){
double decimal = (numerator*1.0)/(1.0*denominator);
return decimal;
}
public String toString(){
reduce(numerator, denominator);
return ((numerator) + "/" + (denominator));
}
}
For some reason the sort() is not working if I used it with a comparator like in the answer it works but I don't understand why this doesn't work. Here is the tester:
public class FractionChecker{
public static void main (String[]args){
int n, d;
Random rand = new Random();
Fraction[] f = new Fraction [20];
for (int j= 0; j<20; j++){
n = rand.nextInt(20);
d = rand.nextInt(19)+1;
f[j] = new Fraction (n,d);
}
System.out.println("Unsorted " + Arrays.toString(f));
Arrays.sort(f);
}
}
Error:
----jGRASP exec: java FractionChecker
Unsorted [7/6, 15/14, 5/15, 8/9, 19/16, 16/5, 11/16, 2/9, 11/10, 10/12, 12/11, 9/18, 15/4, 11/4, 10/7, 12/8, 13/14, 19/5, 19/15, 13/5]
Exception in thread "main" java.lang.ClassCastException: Fraction cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.mergeSort(Arrays.java:1155)
at java.util.Arrays.mergeSort(Arrays.java:1155)
at java.util.Arrays.sort(Arrays.java:1079)
at FractionChecker.main(FractionChecker.java:18)
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
This is the error I am getting when I use Arrays.sort(f) and I am not sure why.
Collections.sort expects a List whose type implements Comparable. You're providing an array of Fraction objects instead.
You should use Arrays.sort instead:
Arrays.sort(f);
If the above throws a ClassCastException for some reason, you can try this version of Arrays.sort, which requires a Comparator as an argument that will do the comparing:
Arrays.sort(f, new java.util.Comparator<Fraction>() {
#Override
public int compare(Fraction f1, Fraction f2) {
return f1.compareTo(f2);
}
});
I don't see your decimalValue code. A better way to compare fractions in any case may be:
long left = numerator * other.denominator;
long right = other.numerator * denominator;
if (left == right) {
return 0;
} else if (left < right) {
return -1;
} else /* if (left > right) */ {
return 1;
}
Not that this will increase your performance drastically but it is just neater and handles division by zero in a sensible way.
The code below works and prints success
import java.util.Arrays;
public class Fraction implements Comparable<Fraction>{
private int numerator;
private int denominator;
public Fraction(int num, int den){
numerator = num;
denominator = den;
}
public int compareTo(Fraction fraction){
if(decimalValue()>fraction.decimalValue()){
return 1;
}else if(decimalValue()<fraction.decimalValue()){
return -1;
}else{
return 0;
}
}
public double decimalValue(){
double decimal = (numerator*1.0)/(1.0*denominator);
return decimal;
}
public String toString(){
return ((numerator) + "/" + (denominator));
}
public static void main(String[] a) {
Fraction[] fractions = new Fraction[2];
fractions[0] = new Fraction(1,1);
fractions[1] = new Fraction(2,3);
Arrays.sort(fractions);
System.out.println("success");
}
}

Rational Number Java Project

For this project I have to create a rational number class that has 2 parts an int numerator and int denominator. I had to add two contractions where the negative denominator has to be moved to the numerator. I also added getters and setters and a toString(). The data should print as numerator/denominator.
I also had to code member methods for addition, subtraction, multiplications, and division and negate(?) I am not sure what that last part means.
I have the class done already but Eclipse is giving me an error with the add and subtract method around the part where I typed "temp". Please let me know if I have anything that is incorrect or if I am missing something.
public class Rational {
private int numerator;
private int denominator;
public Rational()
{
numerator = 0;
denominator = 1;
}
public Rational(int n, int d, int num, int denom)
{
if (d < 0)
{
num = -n;
denom = d;
}
else if (d == 0)
{
num = n;
denom = 1;
}
else
{
num = n;
denom = 0;
}
}
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
public void setNumerator(int n)
{
numerator = n;
}
public void setDenominator(int n, int d, int num, int denom)
{
denominator = d;
if (d < 0)
{
num = -n;
denom = d;
}
else if (d == 0)
{
num = n;
denom = 1;
}
else
{
num = n;
denom = 0;
}
}
public String toString()
{
return numerator + "/" + denominator;
}
public boolean equals (Rational other)
{
if(numerator * other.denominator == denominator * other.numerator)
return true;
else
return false;
}
public boolean notequals(Rational other)
{
if (numerator * other.denominator != denominator * other.numerator)
return true;
else
return false;
}
//subtract method
public Rational subtract(Rational other)
{
Rational temp;
temp.numerator = numerator * other.denominator - denominator * other.numerator;
temp.denominator = denominator * other.denominator;
return temp;
}
//add method
public Rational add(Rational other)
{
Rational temp;
temp.numerator = numerator * other.denominator + denominator * other.numerator;
temp.denominator = denominator * other.denominator;
return temp;
}
public boolean lessThan(Rational other)
{
return(numerator * other.denominator < denominator * other.numerator);
}
public boolean greterThan(Rational other)
{
return(numerator * other.denominator > denominator * other.numerator);
}
public boolean lessThanEqualTo(Rational other)
{
return(numerator * other.denominator <= denominator * other.numerator);
}
public boolean greaterThanEqual(Rational other)
{
return(numerator * other.denominator >= denominator * other.numerator);
}
}
I am however struggling with the main to test each method.
Here is what I have so far:
public class Project4 {
public static void main(String[] args) {
Rational a = new Rational();
Rational b = new Rational();
Rational c;
c = a.add(b);
}
}
//Here goes commented code:
public class Rational
{
private int numerator; // You can declare private variables here all right
private int denominator;
// This constructor creates a new object of the class Rational. Objects are instances of that class, all right?
public Rational()
{
numerator = 0;
denominator = 1;
//private int numerator = 0;
//private int denominator = 1; // I get it, you need them even when not giving arguments, but it is better to do stuff in constructors. You better try to make declarations in the constructor and not in the begining of a class, if possible.
}
// Here is the constructor overriden, so you can create an instance that contains 4 arguments. (n,d,num,denom) Good.
public Rational(int n, int d, int num, int denom)
{
// You repeat yourself in the constructor.
// public void setDenominator(int n, int d, int num, int denom) does the same thing right?
// I don't remember now, but I think that on instantiation you can't use methods, if you don't add the word static.
// public static void setDenominator(int n, int d, int num, int denom) will make you able to call it in the constructor!
if (d < 0)
{
num = -n;
denom = d;
}
else if (d == 0)
{
num = n;
denom = 1;
}
else
{
num = n;
denom = 0;
}
}
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
public void setNumerator(int n)
{
numerator = n;
}
public void setDenominator(int n, int d, int num, int denom) // FIX IT. ADD STATIC
{
denominator = d;
if (d < 0)
{
num = -n;
denom = d;
}
else if (d == 0)
{
num = n;
denom = 1;
}
else
{
num = n;
denom = 0;
}
}
public String toString()
{
return numerator + "/" + denominator;
}
public boolean equals (Rational other)
{
if(numerator * other.denominator == denominator * other.numerator)
return true;
else
return false;
}
public boolean notequals(Rational other)
{
if (numerator * other.denominator != denominator * other.numerator)
return true;
else
return false;
}
//subtract method
public Rational subtract(Rational other)
{
Rational temp;
temp.numerator = numerator * other.denominator - denominator * other.numerator;
temp.denominator = denominator * other.denominator;
return temp;
} // THIS RETURNS temp THAT IS AN OBJECT OF THE TYPE Rational!!! Remember that.
//add method
public Rational add(Rational other)
{
Rational temp;
temp.numerator = numerator * other.denominator + denominator * other.numerator;
temp.denominator = denominator * other.denominator;
return temp;
}// THIS RETURNS temp THAT IS AN OBJECT OF THE TYPE Rational!!! Remember that.
public boolean lessThan(Rational other)
{
return(numerator * other.denominator < denominator * other.numerator);
}// What type is this method return? Here is the gap you must fill. If you learn how to handel what methods return, you will be fine. Try stuff out.
public boolean greterThan(Rational other)
{
return(numerator * other.denominator > denominator * other.numerator);
}
public boolean lessThanEqualTo(Rational other)
{
return(numerator * other.denominator <= denominator * other.numerator);
}
public boolean greaterThanEqual(Rational other)
{
return(numerator * other.denominator >= denominator * other.numerator);
}
}

Math equations returning 0 when using variables between classes

My final result when testing these classes returns zero/zero, but it should return an actual answer.
Here is a small sample of the code.
parent class:
http://pastebin.com/QvxqgrfN
subclass: (here lies the problem - by the way, the main section is for testing results. I will take it out afterwards.)
public class HW6Fraction extends Fraction {
public HW6Fraction(int num, int denom) {
super();
}
public Fraction add(Fraction f) { // Add method
int num = getNumerator() + f.getNumerator();
int denom = getDenominator() + f.getDenominator();
Fraction result = new Fraction(num, denom);
return result;
}
public static void main(String[] args) {
HW6Fraction F1 = new HW6Fraction(4, 7);
HW6Fraction F2 = new HW6Fraction(1, 3);
Fraction F3 = F1.add(F2);
System.out.println("sum=" + F3.getNumerator() + "/" + F3.getDenominator());
}
}
Parent Class
public class Fraction {
private int numerator; //Numerator of fraction
private int denominator; //Denominator of fraction
public Fraction(int num, int denom) { //Constructor
numerator = num;
denominator = denom;
}
public Fraction() { //Constructor w/ no parameters
new Fraction(0, 1);
}
public Fraction(int num) { //Constructor w/ numerator parameter
numerator = num;
int denom = 1;
}
public int getNumerator() { //getNumerator method
return numerator;
}
public int getDenominator() { //getDenominator method
return denominator;
}
public void setNumerator(int num) { //setNumerator method
numerator = num;
}
public void setDenominator(int denom) { //setDenominator method
denominator = denom;
}
public Fraction add(Fraction f) { //Add method
int num = numerator * f.getDenominator() + f.getNumerator() *
denominator;
int denom = denominator * f.getDenominator();
Fraction result = new Fraction(num, denom);
return result;
}
public Fraction subtract(Fraction f) { //Subtract method
int num = numerator * f.getDenominator() - f.getNumerator() *
denominator;
int denom = denominator * f.getDenominator();
Fraction result = new Fraction(num, denom);
return result;
}
public Fraction multiply(Fraction f) { //Multiply method
int num = numerator * f.getNumerator();
int denom = denominator * f.getDenominator();
Fraction result = new Fraction(num, denom);
return result;
}
public Fraction divide(Fraction f) { //Divide method
int num = numerator * f.getDenominator();
int denom = denominator * f.getNumerator();
Fraction result = new Fraction(num, denom);
return result;
}
}
You are not passing arguments to super constructor:
public HW6Fraction(int num, int denom){
super();
}
should be:
public HW6Fraction(int num, int denom){
super(num, denom);
}
otherwise the parent class won't initialize instance variables (they'll be 0 indeed).

Categories