I have
public int compareTo(Object other)
{
}
I need to be able to compare two different sets of numbers and the numbers in the corresponding places.
For example:
Time t1 = new Time(17, 12);
System.out.println(t1);
Time t2 = new Time(9, 45);
System.out.println(t2);
System.out.println("Greater Than:");
System.out.println(t1.compareTo(t2));
And the output would be
1712
0945
Greater Than:
1
In the time class, the first number is hours while the second number is the minutes. I need help comparing the two numbers.
My time class uses
public Time (int y, int x)
{
minute = x;
hour = y;
if (minute>59 || minute<0)
{
minute = 0;
}
if (hour>=24 || hour<0)
{
hour=0;
}
}
How would i compare two new time objects to each other?
First implement the Comparable interface with the correct generic type, in your case Comparable<Time>.
Then you're able to access the other object's attributes.
Your method will now look like this:
public int compareTo(Time otherTime)
{
//... compare things here... like:
return hour.compareTo(otherTime.getHour());
}
This is a sample, you have to implement compare logic yourself, since I don't know if this is an assignment.
The logic has nothing technical. Tell us verbally how you are doing the comparison in your mind when you faced 17:12 & 09:45. If you can speak out in a systematic way, then there should be no problem writing it as code.
I can understand you maybe a total newbie in programming that you have even no clue in writing a most simple line of code. However in programming world, no one is gonna lead you by grabbing your hand to write. You should try to solve it by yourself.
I won't give you a direct answer. However, this is a little example of similar problem. Assume there is a grading system like this, where A1 < A2 < A3 ... < An < B1 < B2 < B3... < C1....
What I am going to do the comparison is, first I will compare the alphabet part, if grade1's alphabet is larger/smaller than grade2's alphabet, I won't need to care about the number part, and I can return -1/1 according to the alphabet being smaller/larger. If the alphabet is the same, then I need to compare the number part, and return 1,-1 and 0 depending on the result.
Then the code will look like something like (half-psuedo code)
public class Grade implements Comparable {
char level; // A,B,C,D
int sublevel; // 1,2,3,4
// ctor, getters/setters etc
#Override
public int compareTo(Grade other) {
// compare the alphabet part
if (this.level < other.level) {
return -1;
} else if (this.level > other.level) {
return 1;
}
// alphabet not larger or smaller, that means equals
// compare the number part
if (this.sublevel< other.sublevel) {
return -1;
} else if (this.sublevel> other.sublevel) {
return 1;
} else { // alphabet and number part are all equals
return 0;
}
}
}
if you can understand what's going on here, then there should be no problem implementing your problem. (Of course there is shorter and cleaner way to implement this. However I think what you need is to learn the basics first)
So your class is Time and i assume it has 2 variables one for minutes and one for seconds. What you need to compare is the t1.minutes to t2.minutes and the t1.seconds to t2.seconds. Your code however is missing a lot of parts and it can't really help us answer your question correctly.
You can use the comparator interface on your Time class.
Doc: http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
There should be plenty of examples online.
Related
I am working on a problem that seems to require backtracking of some sort. I have a working recursion method but stackOverFlow happens with larger inputs. Could this be solved with an iterative implementation? I am trying to implement a method that takes in two target values a and b. starting with a = 1 and b = 1, how many "adds" would it take to reach the target a and b values? adds can either make a = a + b or b = b + a, but not both.
for example, if target a = 2 and target b = 1, it takes 1 "add". a=1 & b=1, a = a + b = 2.
public static String answer(String M, String F) {
return answerRecur(new BigInteger(M), new BigInteger(F), 0);
}
public static String answerRecur(BigInteger M, BigInteger F, int its) {
if(M.toString().equals("1") && F.toString().equals("1")) {
return "" + its;
}
else if(M.compareTo(new BigInteger("0")) <=0 || F.compareTo(new BigInteger("0")) <=0) {
return "impossible";
}
String addM = answerRecur(M.subtract(F), F, its +1);
String addF = answerRecur(M, F.subtract(M), its +1);
if(!addM.equals("impossible")) {
return addM;
}
if(!addF.equals("impossible")) {
return addF;
}
return "impossible";
}
Recursive backtracking works by going through all candidate steps, do a step, recurse, undo the step.
This means that if a solution takes N items, ideally the recursion depth will not exceed N.
So: an overflow is not expected, probably too much is tried, or even infinitely recurring.
However in your case a BigInteger might be sufficient large and when using small steps (1) one would have a very recursion depth. And every call creates sufficient much. Better would be int or long instead of BigInteger.
In every call you have two candidates:
M.subtract(F)
F.subtract(M)
You evaluate both, one could stop when a result was found.
Also intelligence (of the math!) is missing: nice would be to prevent too many steps, finding as directed as possible a solution. In general this can be achieved by some way of sorting of the (2) candidates.
How one comes at a smart solution? First the math must be readable, what BigInteger is less. Try some sample solutions by hand, and look for a smart approach to order the attempts.
You can cut the recursion short, assuming keeping M and F positive:
if (M.compareTo(BigInteger.ZERO) <= 0 || F.compareTo(BigInteger.ZERO) <= 0) {
return "impossible";
}
if (M.equals(BigInteger.ONE)) {
return String.valueOf(F.intValue() - 1 + its);
}
if (F.equals(BigInteger.ONE)) {
return String.valueOf(M.intValue() - 1 + its);
}
The same can be done with integer division (and modulo):
if (M.compareTo(F) > 0) {
String addM = answerRecur(M.mod(F), F, its + M.divided(F).intValue());
}
Thinking of an iterative solution actually is possible here despite more than one recursive call, but it would not add to the quality.
Remarks:
by java convention one should use f and m for variable names.
is BigInteger really required? It causes a bit awkward code.
Say, I'm making a simple badugi card game where the Hand is represented by 10 characters in a string. E.g:
2s3h5dQs - 2 of spades, 3 of hearts, 5 of diamonds, Queen of spades
Now, in this badugi card game I want to create two loops where the first loop checks if all the ranks are different(none of them can be the same) and the other loop checks if all the suits are different. If both of these conditions return as true where they all have different ranks and suits, the hand has drawn a badugi(please excuse my lack of terminology where necessary.)
Now, how can I create an efficient loop for such a situation? I was thinking that I could create several if statements as such:
if (hand.charAt(0) != hand.charAt(2) && hand.charAt(0) != hand.charAt(4) && hand.charAt(0) != hand.charAt(6))
if (hand.charAt(2) != hand.charAt(0) && hand.charAt(2) != hand.charAt(4) && hand.charAt(2) != hand.charAt(6))
... and so forth comparing every single index to one another. But this gets tedious and seems very unprofessional. So my question is, how do I write an efficient loop for this scenario? How can I compare/check if there are no matches at these specific index points to one another?
If I haven't explained properly then please let me know.
Please keep in mind, I am not allowed freedom of how to formulate a hand. It has to be in the format above
You are putting your energy into the wrong place.
You do not need to worry about efficiency at all.
Instead, you should worry about creating a clean design (based on reasonable abstractions) and then write code that is super-easy to read and understand.
And your current approach fails both of those ideas; unfortunately completely.
In other words: you do not represent hands and values as characters within a String.
You create a class that abstracts a Card (with its value and face).
And then a "hand" becomes a List / array of such Card objects. And then you can use concepts such as Comparator to compare card values, or you can make use of equals() ...
And even when you wish to keep your (actually over-complex) naive, simple approach of using chars within a string; then you should at least use some kind of looping so that you don't compare charAt(0) against charAt(2); but maybe charAt(i) against charAt(j).
And following your edit and the excellent comment by jsheeran: even when you are forced to deal with this kind of "string notation"; you could still write reasonable code ... that takes such string as input, but transforms them into something that makes more sense.
For example, the Card class constructor could take two chars for suite/value.
But to get you going with your actual question; you could something like:
public boolean isCardDistinctFromAllOtherCards(int indexToCheck) {
for (int i=0; i<cardString.length-1; i+=2) {
if (i == indexToCheck) {
continue;
}
if (cardString.charAt(indexToCheck) == cardString.charAt(i)) {
return false;
}
}
return true;
}
( the above is just an idea how to write down a method that checks that all chars at 0, 2, 4, ... are not matching some index x).
You should really think about your design, like creating Card class etc., but back to the question now, since it's not gonna solve it.
I suggest adding all 4 values to a Set and then checking if size of the Set is 4. You can even shortcut it and while adding this yourSet.add(element) return false then it means there is already that element in the set and they are not unique. That hardly matters here since you only need to add 4 elements, but it may be useful in the future if you work with more elements.
I would advice creating an array with these chars you are referencing just to clean up the fact you are using indices. i.e create a vals array and a suits array.
This would be my suggestion by using a return or break the loop will stop this means when a match is found it wont have to loop through the rest of the elements .. Hope this helps !
private static int check(char[] vals, char[] suits){
int flag;
for(int i=0; i<=vals.length-2;i++){
for(int k=vals.length-1; k<=0;k++){
if(vals[i]==vals[k]){
flag=-1;
return flag;
}
if(suits[i]==suits[k]){
flag=1;
return flag;
}
}
}
return 0;
}
Why not simply iterate over your string and check for same ranks or suits:
public class NewClass {
public static void main(String[] args) {
System.out.println(checkRanks("2s3h5dQs"));
System.out.println(checkSuits("2s3h5dQs"));
}
public static boolean checkRanks(String hand){
List<Character> list = new ArrayList<>();
for (int i = 0; i< hand.length(); i+=2){
if (!list.contains(hand.charAt(i))){
list.add(hand.charAt(i));
}
else{
return false;
}
}
return true;
}
public static boolean checkSuits(String hand){
List<Character> list = new ArrayList<>();
for (int i = 1; i< hand.length(); i+=2){
if (!list.contains(hand.charAt(i))){
list.add(hand.charAt(i));
}
else{
return false;
}
}
return true;
}
}
For example I have this array:
int[] a = {1,1,1,1,5,5,1,1,1};
//output: 4 2 3
In other words, it will print the sequences of the same number.
I have already tried this:
int doubles_count_while (int a[][], int n, int cestatic) {
int result = 1;
while (result < n && a[result - 1][cestatic] == a[result][cestatic]) {
result++;
}
return result;
}
int doubles_groups(int a[][], int n, int cestatic, int b[]) {
int result = 0;
int i = 0;
while (i < n) {
int z = doubles_count_while(a, n-i, a[i][cestatic]);
b[result++] = z; i += z;
}
return result;
}
When posting code, please post it as an MCVE so that we can actually run it. You should also tell us what you expect this code to do and what it does instead. Try to narrow it down to a single line of code that's not doing what you expect it to do.
This is a pretty broad question, but I'll try to help in a general sense. You need to take a step back and forget about the code for a second. Write down the steps you would follow, without a computer, if somebody handed you a stack of index cards with numbers written on them and asked you to group them. How exactly would you do that?
Pretend you have a really dumb friend who has no idea how to group the cards. You should be able to hand your instructions to that friend and have them follow them to group the cards without any help from you. Remember how dumb this friend is, so make sure your instructions are as small as possible.
When you have those instructions written out, that's an algorithm that you can start thinking about implementing with code. Trying to dive into the code without a clear idea of what you want it to do is just going to give you a ton of headaches. Good luck.
Question:
How many calls are needed to recursively calculate the 7th Fibonacci value?
So this was a problem given to me and the answer was given to me as 41. Then I went to a professor because I didn't understand it, but I was given another answer. I think it was 25? (don't quote me on that) Then I went to another professor... and he told me the person who gave you this problem should have given you the sample code because there can be multiple ways to write this recursive function which would result in different amounts of calls.
So if this is true can you guys find different recursive functions that would result in a different amount of calls needed to get the 7th value of the sequence?
One way:
static long fibonacciR(int i)
{
if (i <= 1)
return i;
return fibonacciR(i - 1) + fibonacciR(i - 2);
}
Another way:
static final int f[] = {0,1,1,2,3,5,8,13,21,34,55,89,144};
static long fibonacciR2(int i)
{
if (i < f.length)
return f[i];
return fibonacciR2(i-1)+fibonacciR2(i-2);
}
In fact 'another' way is any number of other ways, depending on how big you make the table. When the table has two elements both methods are equal. When it has three there are 25 calls. When 4, 15. And so on.
Yet another way, to get specifically 25 calls:
static long fibonacciR3(int i)
{
if (i == 0)
return 0;
if (i <= 2)
return 1;
return fibonacciR(i - 1) + fibonacciR(i - 2);
}
I wanted to do this exercise that professor gave to our class but I don't know how to do it:
Write a method, called first, that returns the most small prime number between 90 and 150.
Well that could be quite easy...if I could use loops like for or similar but i can't. I can just use if, Array, Method and other really basic things, no libraries.
The only 2 solution that i found is to write around 60 IF or just to write
int prime(){
return 97;
}
Please help me to do it or I have to deliver it in this last way :'D
You can do it without traditional "loops" by making a recursive function, a function that calls itself. Here's some pseudo code:
int nearestPrime(int val) {
if (val is prime) {
return val;
} else {
return nearestPrime(val + 1);
}
}