I need a way of putting a fraction into an ArrayList. I am having problems however because I'm not sure how I could do this in a way that I could later compare them so they can be sorted.
Note: I will be using 4 or more fractions and I'm not too sure how to (if its possible) to use the comparable class to do it for more than 2.
For example:
I need to input 1/1 , 3/4 , 7/4 , 2/8
I then need to sort them (Using the list) from the smallest to the greatest.
Any help is appreciated.
Create a class called Fraction which stores two variables: numerator and denominator.
You can then make an ArrayList of Fractions.
If you'd like to sort them easily, your best bet is to have it implement Comparable.
public class Fraction implements Comparable<Fraction> {
private int x1, x2; // implement get/set
public int compareTo(Fraction o) {
double tmp = Math.abs((double)x1 / x2 - (double)o.x1 / o.x2);
if (tmp < 0) return -1;
if (tmp < 1e-9) return 0;
return 1;
}
}
Now:
ArrayList<Fraction> f;
Collections.sort(f);
You can do it two ways first you can take fractions as float value otherwise make a class representing the fraction value then make another class implement Interface Comparator.And then use Collections to sort.
Related
I'm trying to write a program that "solves a circle". The Circle class contains an ArrayList of Triangle Objects and an ArrayList of Integers. The Triangle objects each have three int instance fields that represent three numbers at the vertices of each triangle. There is also a Pairs class (you can see all of the code I have in the "code" section)
Here is an example of the setup using four triangles that is not solved:
And here is the same circle after it has been "solved":
The Circle in the second picture is a solved Circle because the number on any arc of the circle is equal to the sum of the two vertex numbers next to it: 6 = 1+5, 15 = 6+9, 11 = 7+4, and 9 = 5+4. Note that this was obtained by rotating the given triangles. This is analagous in the code to simply changing the Pair that is present in the solution for each triangle (where a "Pair" is an object of two ints, where those ints are the values on the circle for each triangle)
A Circle isn't always given in a "solved" state. If this is the case, the triangles can be rotated so that the circle will be in the solved state. The precondition of any given circle is that there is a solved state, so the numbers will always line up.
A circle will always have at least two triangles and there is no (practical) maximum number. Every given circle will always be solvable, meaning there is a way to rotate each triangle so that the number on the circle is the result of the sum of the two adjacent vertices from the two different triangles.
The point of the program is not to alter any of the given instance fields; instead, I just want to create a method called solveCircle that returns an ArrayList of Pairs that represents the solution to the Circle. In the above example, the solveCircle method would return an ArrayList containing the following pairs: (4,1), (5,6), (9,7), (4,5). These pairs are in the solution because they are all pairs of numbers on a triangle, and each pair is also on the circle. Note that the solution goes counter-clockwise around the circle.
My gut is telling me that this process should involve some type of recursion, since a loop would be tricky due to the circular nature of the circle; in other words, I could loop through each pair of triangles finding the proper solution, but there could easily be more than one, and comparing each one with the solution to the next sum seems like it will be inefficient; recursion seems like a better option but I'm not sure what to apply the recursion to...what alrgorithm should I use and what is even the base case?
public class Triangle
{
private int num1;
private int num2;
private int num3;
public Triangle(int n1, int n2, int n3)
{
num1 = n1;
num2 = n2;
num3 = n3;
}
public ArrayList<Pair> getPairs()
{
ArrayList<Pair> pairs = new ArrayList<Pair>();
pairs.add(new Pair(num1, num2));
pairs.add(new Pair(num2, num3));
pairs.add(new Pair(num3, num1));
return pairs;
}
}
class Pair
{
private int p1;
private int p2;
public Pair(int x, int y)
{
p1 = x;
p2 = y;
}
}
public class Circle
{
private ArrayList<Triangle> triangles;
private ArrayList<Integer> sums;
public Wheel(ArrayList<Integer> s, ArrayList<Triangle> t)
{
triangles = t;
sums = s;
}
public ArrayList<Pair> solveCircle()
{
//need help here
}
}
You can use a tree to separate the triangles that are solved from the ones that are unsolved. The same for the circles that are solved and that are unsolved. This way, you would make it a log n search function that would ignore the solved ones, thus avoiding unnecessary comparisons.
if (solved)
add to left side of the tree
else
add to right side of the tree
The complexity as well for this could be an extreme overkill depending on the use case.
for the initial step, you call the helper three times: once for each pair, until a success is returned (boolean could be used to indicate success.)
the helper performs the recursive step.
for the recursive step, you have a sum extending behind you, an integer which you must combine with to meet that sum, and three possible ways to acheive it... however you do not return success unless your recursive call also returns success
for the terminal step, there is no rotating allowed, just a final true or false for did I complete the sum behind me.
I am dividing two ints x/y,. Say 3/2. Then one would get 1 as result though the actual result is 1.5. Ok this is obvious as it's int division. But I want 1.5 to be rounded off to the next highest int not the immediate lowest. So 2 is desired as result. (One can write simple logic using mod and then division... But am looking for simple Java based API). Any thoughts?
You can, in general, write (x + y - 1) / y to get the rounded-up version of x/y. If it's 3/2, then that becomes (3 + 2 - 1) / 2 = 4 / 2 = 2.
You can use the ceil (ceiling) function:
https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil(double)
That will essentially round up to the nearest whole number.
If you can change the datatype to double, following is the best solution -
double x = 3;
double y = 2;
Math.ceil(Math.abs(x/y));
This will give you 2.0
import java.lang.Math;
//round Up Math.ceil(double num)
//round Down Math.floor(double num)
public class RoundOff
{
public static void main(String args[])
{ //since ceil() method takes double datatype value as an argument
//either declare at least one of this variable as double
int x=3;
int y=2; //double y =2;
//or at least cast one of this variable as a (double) before taking division
System.out.print(Math.ceil((double)x/y)); //prints 2.0
//System.out.print(Math.ceil(x/y));
}
}
So I need to change doubles such as 143.203030 to 143.20 rounding the second digit up or down(like money) my plan was to turn the double into an array and then if the third number after the decimal is 5 or greater the previous element would be one greater than it was. How do i access each int of a double and how would i turn my array of int back into doubles. Now... This is obviously a terrible and inefficent way, what would be a better idea. I would take the time to code that but I figured explaining it and asking for a better way is the same thing. Well actually i couldn't code that because I dont know to access each part of a double.
Try this:
public static roundHundredth(double d) {
return (double)((int)(d*100)+.5)/100;
}
A better idea, especially if you are working with money, is to use the BigDecimal class. It supports a variety of rounding modes meeting most common financial and engineering requirements.
To meet your immediate needs, you can use BigDecimal as follows (although it may be best to eliminate the double type from your program and use BigDecimal throughout):
String[] round(double[] arr) {
String[] r = new String[arr.length];
for (int idx = 0; idx < arr.length; ++idx) {
r[idx] = BigDecimal.valueOf(arr[idx]).setScale(2, RoundingMode.HALF_UP).toString();
}
}
I agree that you shouldn't use a double to store a money value (although will probably work OK for smaller amounts). The general approach for doing this kind of rounding is
double rounded = Math.round(d * 100) / 100.0;
I currently have a function which will take an input and round it to 4 decimal places, it looks like this:
public static double table_round(double n) {
return (double) Math.round(n * 10000) / 10000;
}
really really simple function, however I was thinking I could change it to allow a second variable to be passed that says how many places to round to, however I'm not sure exactly how to go about printing the correct number of 0's in the math statement there (each 0 represents one decimal place that will be printed). Any ideas on how this could be accomplished? This is just some extra credit stuff for my java class, I'm still learning so I'm sorry if there is a simple solution I'm overlooking.
public static double table_round(double n, int digits) {
return BigDecimal.valueOf(n).setScale(digits,BigDecimal.ROUND_HALF_UP).doubleValue();
}
You can use BigDecimal and its setScale() method to fix no of digits after decimal
public static double table_round(double n) {
// No of digits you want after decimal.
int digitsAfterDecimal = 5;
BigDecimal bigDecimal = BigDecimal.valueOf(n);
// BigDecimal.ROUND_FLOOR is Rounding Mode..denote how your value is rounded off
// Other ways are:- "ROUND_CEILING", "ROUND_DOWN", etc..
bigDecimal = bigDecimal.setScale(digitsAfterDecimal, BigDecimal.ROUND_FLOOR);
return Double.valueOf(bigDecimal.toString());
}
For detailed information, see http://www.opentaps.org/docs/index.php/How_to_Use_Java_BigDecimal:_A_Tutorial
Is quaternion comparison possible? I'm writing a Java class of Quaternions and I want to implement the Comparable interface to use the Collections.sort(List<Quaternion>) facility. I'm not expert at math, I really don't understand the things I read about Quaternions. So, can anyone tell me can I override the compareTo method for Quaternions and how?
My class declarition:
public class Quaternion implements Serializable, Comparable<Quaternion> {
private double s; // scalar part
private double i, j, k; // vectorel part
public Quaternion() {
super();
}
public Quaternion(double s, double i, double j, double k) {
super();
this.s = s;
this.i = i;
this.j = j;
this.k = k;
}
You can implement compareTo, by comparing its fields. However, you need to determine what you want the order to be like. AFAIK, there is no standard definition of what comes before or after for complex numbers let alone a quaternion.
You certainly can compare them; whether the comparison is meaningful or not is open to debate. Since a quaternion can represented by four real numbers, you'd just do something like (pseudocode)
if (q1.a != q2.a)
return q1.a - q2.a;
else if (q1.b != q2.b)
return q1.b - q2.b;
else if (q1.c != q2.c)
return q1.c - q2.c;
else
return q1.d - q2.d;
Since the values are real numbers, you might use an epsilon-based comparison, and you need to convert small positive and negative differences into positive and negative integers. But you get the idea.
There is no reason why you can't compare two quaternions. Assuming that you want to compare magnitudes, compute and compare the Quaternion Norms. Your Quaternion class should have a norm (magnitude) method allowing a toCompare to be something like the following:
int compareTo(Quaternion o){
return (int)(this.norm() - o.norm());
}
A better version would be:
int compareTo(Quaternion o){
// return (int)(this.norm() - o.norm());
double tNorm = this.norm;
double oNorm = o.norm;
int retVal = 0;
if (tNorm < oNorm){
retVal = -1;
} else if (tNorm > oNorm){
retVal = 1;
}
return retVal;
}
A quaternion is a kind of 4-dimensional vector.
How do you want to order them? The most reasonable way would be to use the norm.
public int compareTo(Object o) {
if (o instanceOf Quaternion) {
// Compute the difference between the square of the norm
double result = s*s + i*i + j*j + k*k - o.s*o.s - o.i*o.i - o.j*o.j - o.k*o.k;
if (result > 0) { return 1; }
if (result < 0) { return -1; }
return 0;
}
}
Note that using the norm will make quaternions of equal length but pointing in different directions equal, and some algorithms will not be able to distinguish between them. Sorting algorithms may well throw away "duplicates". Just a friendly warning.
Think about quaternions as a tuple (ordered list) of four floating-point numbers. Defining equality is pretty straightforward, but how would you define total order? In other words, how do you want to define greater-than relationship between two four-number sequences?
In fact, there is no common greater-than relationship even between complex numbers and quaternions can be considered as a pair of complex numbers. Easy comparison is only possible in one-dimensional space. Complex numbers are two-dimensional, quaternions - four.
You can, but I don't think you should.
The argument is the same as for complex numbers. Given two quaternions, they are either equal or not, there is no way to say which one is greater than the other. The quaternions form a division algebra, which is not ordered (unlike the field of the real numbers for example). The only (reasonable) way, I can think of, comparing two quaternions is by using the norm.
double norm = Math.sqrt(s*s + i*i + j*j + k*k);
In that case you could define, that a quaternion a is greater than a quaternion b iff the norm of a is greater than the norm of b. But that is definitely not a standard definition. I would be careful in making quaternions or complex numbers comparable. However, it depends on your use case. Just take into account, that there is no standard way of sorting such numbers.
See this google search for some good links about comparing complex numbers. The argument for quaternions is basically the same.
Another way to compare quaternions would be to use a lexicographic order.
There is no mathematical standard ordering for quaternions or for complex numbers.
You may nevertheless want to implement the Comparable interface, for conveniently sorting and for storing them in TreeSet and TreeMap collections.
To make clear that the ordering is arbitrary I'd use the lexicographic combination of the components of the quaternion. This also ensures that the ordering is consistent with equals, and that the algorithms work as desired.
For a more natural ordering, for example one that takes the norm into account, you can always explicitly define a comparator.