Why are these functions incorrect and how can I change it to pass the tests with recursion and no lists. public class Bl

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Why are these functions incorrect and how can I change it to pass the tests with recursion and no lists. public class Bl

Post by answerhappygod »

Why are these functions incorrect and how can I change
it to pass the tests with recursion and no lists.
public class Block {
public int id; // Number
public int rank; // position in the Chain
public Block next;
// attributes to be added
public int size;
public Block(int id, int rank) {






this.id = id;
this.rank = rank;
this.next = null;
// attributes to be
added

}







public Block(int id, int rank, Block next)
{






this.id = id;
this.rank = rank;
this.next = next;
// attributes to be
added

}
// Additional constructors may be added
// DO NOT MODIFY
public String toString() {






String str = "(" + id + ", "
+ rank + ")";
if (this.next == null)
{
return
str;
}
return str + " -> " +
next.toString();
}
* @return true if the chain starting at the current node
is a valid Collatz
* chain and false
otherwise. For a chain to be valid, it needs to
* follow the 3n+1
rule but not necessarily have a valid rank. The fast
* collatz chain
should be treated as invalid.
*/






public boolean isValid() {

if(this.next == null) {
return
true;
}
else
if(this.id % 2 == 0 && this.id / 2 == this.next.id) {
return
next.isValid();
}
else
if(this.id % 2 == 1 && this.id * 3 + 1 == this.next.id)
{
return
next.isValid();
}
else
{
return
false;
}
}



/**






* IMPORTANT: Even thought this method is in the
Block class, it may be harder
* than most in the Chain class.
*
* @return true if the chain starting at the
current node is either a valid
* Collatz chain or
a fast Collatz chain. In this question, you also
* need to ensure
that the rank is valid. A valid rank starts at 1 and
* increases with
one.
*/






public boolean isValidAdvanced() {

if(next == null) {
return
false;
}
else
if(next.id % 2 == 0 && next.id / 2 == id &&
next.rank == rank + 1) {
return
isValidAdvanced();
}
else
if(next.id % 2 == 1 && next.id * 3 + 1 == id &&
next.rank == rank + 1) {
return
isValidAdvanced();
}
else
{
return
false;
}

}





}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply