Object oriented programming comparing linkedlists - java

I have objects of class Bit which is basically a class that has one field called value and it's boolean.
public class Bit {
private boolean value;
public Bit() {
this.value = false;
}
public Bit(boolean value) {
this.value = value;
}
public boolean getValue() {
return value;
}
}
and it has some more methods.
and then I have a class called number which is supposed to represent large number in their binary representation using a linked list where the firstlink is the LSB and the lastlink is the MSB.
for instance if I call the constructor
Number num1 = new Number(6);
then I'll have a linked list like the following : 0 1 1 (null)
Now I wanna know how to be able to compare two Number objects.
so for example: if I have num1, and Number num2 = new Number (7); [ 1 1 1 ]
then I want a method to tell me that num2 is larger than num1
to compare two binary numbers simply I would start with the MSB and compare each bit and once one is larger than the other that means the number is larger.
I could easily get the integer value of each Link(Bit) using Bit.toInt();
So I was thinking of iterating over the list and comparing the bits one by one , problem is that my iterator stars before firstlink (LSB) , I know I could move it all the way to the end and start iterating using hasPrevious() but I don't have that method.
I wanna be able to do that while only going over each list once.
Any ideas?
public static boolean lessEq(Number num1, Number num2){
Iterator<Bit> it1 = num1.bitIterator().;
Iterator<Bit> it2 = num2.bitIterator();
}
Number constructors:
public Number(){
list = new LinkedList<Bit>();
list.add(new Bit(false));
}
/**
* Constructs a new Number from an int.
* #param number an int representing a decimal number
*/
public Number(int number) { // assignment #1
list = new LinkedList<Bit>();
if(number == 0) list.add(new Bit(false));
if (number < 0) throw new IllegalArgumentException("number cannot be negative");
else {
while (number > 0) {
if (number % 2 == 0) {
list.add(new Bit(false));
}else list.add(new Bit(true));
number = number / 2;
}
}
}
Edit: it Works Thanks very much for the comments !

Initially you assume that both numbers are equal.
You get bits from both numbers. Use zero if either was exhausted.
If both bits are equal, you don't alter the result.
If bit from number A is 1, then set number A to be larger.
If bit from number B is 1, then set number B to be larger.
If both lists are exhausted, return result.
Otherwise repeat from step 2.
This takes into account the case where you allow lists with unnecessary zero bits as MSB.
If you want to submit fancy homework you can start from the end, keep track of the index you're at and stop at the first comparison where the bits are not equal.

You can do an obvious thing: collect the bits in an array, then walk the two arrays backwards. Or, you can use recursion, and use the stack for storage:
public int compareTo(Number other) {
Iterator<Bit> it1 = this.bitIterator();
Iterator<Bit> it2 = other.bitIterator();
return bitCompareTo(it1, it2);
}
private static int bitCompareTo(Iterator<Bit> it1, Iterator<Bit> it2) {
if (!it1.hasNext() && !it2.hasNext()) return 0;
boolean b1 = it1.hasNext() ? it1.next().getValue() : false;
boolean b2 = it2.hasNext() ? it2.next().getValue() : false;
int cmp = bitCompareTo(it1, it2);
if (cmp != 0) return cmp;
else return Boolean.compare(b1, b2);
}
This traverses each iterator only once, but since the comparison logic is after the recursive call, you get the comparisons done as they are popped off the call stack - in reverse order, just like we want them.
Basically: If we reach the end of both iterators at the same time, we're undecided on length alone, and signal that with 0, and we kick off our recursive decision-making. (If we reach the end of one iterator sooner, we assume false to left-pad that number with zeroes.) In each recursive step, if we've decided (whether on length or on a higher bit pair), we just pass that decision along. If the higher bits were undecided, we try to compare the current bit pair (and if it's equal, Boolean.compareTo will return 0, telling the next level down that we're still undecided). If we inspected all bits and we're still undecided, we'll just say 0 now stands for "equal" - precisely what compareTo should return in that case.
Once you have compareTo, it is trivial to define the other relational operators.

I think you should try this:
public static boolean lessEq(Number num1, Number num2) {
LinkedList<Bit> bits1 = num1.list;
LinkedList<Bit> bits2 = num2.list;
if(bits1.size() == bits2.size()) {
for(int i = bits1.size() - 1; i >= 0; i++) { // reversed loop since the MSB is at the end of the list
Bit bit1 = bits1.get(i);
Bit bit2 = bits2.get(i);
if(bit1.getValue() != bit2.getValue()) {
if(bit1.getValue()){ // can be replaced with return !bit1.getValue() if you want
return false; // bit1's actual bit is true, bit2 is false, so bit1 is greater
} else {
return true;
}
}
}
return true; // all bits are the same
} else {
if(bits1.size() > bits2.size()) { // can be replaced with return bits1.size() <= bits2.size() if you want
return false; // first number has more elements, so it's greater
} else {
return true;
}
}
}
EDIT
According to comments you can do the following instead (using iterators)
public static boolean lessEq(Number num1, Number num2) {
Iterator<Bit> bits1 = num1.list.descendingIterator();
Iterator<Bit> bits2 = num2.list.descendingIterator();
while(bits1.hasNext() && bits2.hasNext()){
Bit bit1 = bits1.next();
Bit bit2 = bits2.next();
if(bit1.getValue() != bit2.getValue()) {
return !bit1.getValue();
}
}
return bits2.hasNext();
}

There’s no real problem in comparing from the least significant bit. You just need to keep track of the difference found so far, and discard it if you find a difference on a higher-order (more significant) bit. It’s easiest to do it recursively:
public class Number implements Comparable<Number> {
/** Linked list of bits, least significant bit first */
Node lsb;
public Number(int n) {
if (n < 0) {
throw new IllegalArgumentException("Negative numbers not supported, got " + n);
}
if (n == 0) {
lsb = null;
} else {
lsb = new Node(new Bit(n % 2 != 0));
n /= 2;
Node tail = lsb;
while (n > 0) {
Node newNode = new Node(new Bit(n % 2 != 0));
n /= 2;
tail.setNext(newNode);
tail = newNode;
}
}
}
#Override
public int compareTo(Number other) {
return compare(lsb, other.lsb, 0);
}
private int compare(Node left, Node right, int diffSoFar) {
if (left == null) {
if (nonZero(right)) {
return -1;
} else {
return diffSoFar;
}
}
if (right == null) {
if (nonZero(left)) {
return 1;
} else {
return diffSoFar;
}
}
int localDiff = Boolean.compare(left.getData().getValue(), right.getData().getValue());
if (localDiff != 0) {
diffSoFar = localDiff;
}
return compare(left.getNext(), right.getNext(), diffSoFar);
}
private boolean nonZero(Node list) {
if (list == null) {
return false;
}
if (list.getData().getValue()) {
return true;
}
return nonZero(list.getNext());
}
}
Example use:
Number six = new Number(6);
Number seven = new Number(7);
System.out.println("Comparing 6 and 7: " + six.compareTo(seven));
System.out.println("Comparing 15 and 6: " + new Number(15).compareTo(six));
Output:
Comparing 6 and 7: -1
Comparing 15 and 6: 1
I am assuming the following Node class:
public class Node {
private Node next;
private Bit data;
// Constructor, getters, setters
}

Related

How to prevent a recursive method from changing a value of a variable?

I'm learning Java, and I'm stuck on a recursion problem.
I need to use a recursive method to check if a number is an Armstrong number or not.
My code:
public class ArmstrongChecker {
public boolean isArmstrong(int number) {
// check if the number is a negative number
if (number < 0) {
return false;
}
ArmstrongChecker armstrongChecker = new ArmstrongChecker();
// find the length of the number
int length = armstrongChecker.lengthChecker(number);
// create a variable to store the sum of the digits of the number
int sum = 0;
// find the individual digits and raise to the power of the numbers of digits
if (number != 0) {
int digit = Math.floorMod(number, 10);
int powerRaised = (int) Math.pow(digit, length);
sum = sum + powerRaised;
isArmstrong(number / 10);
}
return sum == number;
}
// method to check the length of the number
public int lengthChecker(int number) {
int length = String.valueOf(number).length();
return length;
}
}
How do I prevent int length in isArmstrong() method from changing its value.
While you are not changing it's value in the posted code, you could mark that variable to be a constant. This way the compiler can error out if you tried to assign a new value.
final int length = armstrongChecker.lengthChecker(number);
As I've already said in the comments, your solution has the following issues:
The result of the recursive call isArmstrong() is being ignored;
There's no need for spawning new instances of ArmstrongChecker. And this method doesn't require object creation at all, it can be implemented as static.
Checking if the number is an Armstrong number boils down to calculating its Armstrong sum, the solution will be cleaner if you implement only this part using recursion.
It might look like this:
public static boolean isArmstrong(int number) {
if (number < 0) return false;
if (number < 10) return true;
return number == getArmstrongSum(number, String.valueOf(number).length());
}
public static int getArmstrongSum(int number, int power) {
if (number == 0) {
return 0;
}
return (int) Math.pow(number % 10, power) + getArmstrongSum(number / 10, power);
}
main()
public static void main(String[] args) {
System.out.println(isArmstrong(370)); // true
System.out.println(isArmstrong(12)); // false
System.out.println(isArmstrong(54)); // false
System.out.println(isArmstrong(153)); // true
}
Output:
true
false
false
true
You need to get the length once for whole recursion, so the cleanest approach would be to pass down both the number and the length into the recursion. An easy way to do this is to have one method that is the public face of the API, and another that does the recursion.
public class ArmstrongChecker {
public boolean isArmstrong(int number) {
if (number < 0) {
return false;
}
int length = lengthChecker(number);
int sum = armstrongSum(number, length);
return sum == number;
}
private int armstrongSum(int number, int length) {
int sum = 0;
if (number != 0) {
int digit = Math.floorMod(number, 10);
int powerRaised = (int) Math.pow(digit, length);
sum += powerRaised;
sum += armstrongSum(number / 10, length);
}
return sum;
}
public int lengthChecker(int number) {
int length = String.valueOf(number).length();
return length;
}
}
This is pretty common in recursion, where the parameters to the recursive part of the algorithm are a little different (usually there are more of them) than what you want a client of the API to have to pass in. The number changes in each recursive call, where number / 10 is passed down, but the same length is passed all the way through.
Notice that the recursive armstrongSum uses the return value from the recursive call, and that there is no need to create another instance of ArmstrongChecker when you are already in an instance method of the class.

How to use binary search of a sorted list and then count the comparisons

I am trying to use my sorted list and implement it with binary search. Then i want to count the number of comparisons it takes to find the key. my code is:
public class BinarySearch {
private static int comparisions = 0;
public static void main(String[] args) {
int [] list = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int i = BinarySearch.BinSearch(list, 20);
System.out.println(comparisions);
}
public static int BinSearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
int mid = (high + low) / 2;
if (key < list[mid]) {
high = mid - 1;
comparisions++;
} else if (key == list[mid]) {
return mid;
comparisions++;
} else {
low = mid + 1;
comparisions++;
}
return -1;
}
}
So far it only gives me 1 for the comparison no matter what number is the key.
Your code is missing the looping part of the search, that looping can either be done using recursion or using a while loop. In both cases you have to ask yourself wether or not you just want to know the count or actually return the count of comparisons. Since your method right now returns the index, it cannot easily return the count of comparisons at the same time. For that to work you either need to return an array of two ints or a custom class IndexAndComparisonCount { ... }.
If you use a recursive approach you need to increment whenever you do a comparison and when you do a recursive call you need to get the return value of that recursive call and increment the comparisonCount the call returned by 1:
if (... < ...) {
IndexAndComparisonCount ret = BinSearch(...);
ret.comparisonCount += 1;
return ret;
} else if (... > ...) {
IndexAndComparisonCount ret = BinSearch(...);
ret.comparisonCount += 2; // since you did compare twice already
return ret;
} else {
return new IndexAndComparisonCount(mid, 2); // you compared twice as well
}

Comparison for BigInteger not working

I'm not getting the output that I'm expecting. This is for a primality test. I'm not really sure what's wrong. Either my loop isn't working correctly, or this isn't.
n is a BigInteger. It's a random generated by user inputted length.
public static boolean isPrime(BigInteger n) {
BigInteger zero = new BigInteger("0");
BigInteger one = new BigInteger("1");
BigInteger two = new BigInteger("2");
BigInteger three = new BigInteger("3");
System.out.println(n + " Mod 2 " + n.mod(two));
if (n.compareTo(one) == 0 || n.compareTo(one) < 0) {
//System.out.println("HIT1");
return false;
} else if (n.compareTo(three) == 0 || n.compareTo(three) < 0) {
//System.out.println("HIT2");
return false;
} else if ((n.mod(two)).compareTo(zero) == 0 || (n.mod(three)).compareTo(zero) == 0) {
//System.out.println("HIT3");
return false;
} else {
System.out.println("Heres n : " + n);
return true;
}
}
Here's my loop. I know for sure that my number generator works though.
do {
num1 = generateNumber(p);
} while (isPrime(generateNumber(p)) == false);
do {
num2 = generateNumber(q);
} while (isPrime(generateNumber(q)) == false);
Don't test if the result of compareTo() equals -1. When you want to mean a < b, you should write a.compareTo(b) < 0. Always compare with 0, not any other constant.
Just realized what the issue was. I'm generating two different numbers in the loop and inside the loop. I was also incorrectly assigning the BigInteger incorrectly in the loop. I should be doing
num1 = new BigInteger(generateNumber(p).toString());
First, test if the number is 2 (if it is, then it is prime). Next, test if the number is divisible by 2 (if it is, then it is not prime). Next, iterate from 3 to the square root of the number in increments of 2 testing for divisibility with the original number (if it is, then it is not prime). Otherwise, the number is prime. Something like,
public static boolean isPrime(BigInteger n) {
final BigInteger two = new BigInteger("2");
if (n.equals(two)) {
return true;
}
if (n.mod(two).equals(BigInteger.ZERO)) {
return false;
}
for (BigInteger i = two.add(BigInteger.ONE); i.multiply(i).compareTo(n) < 1;
i = i.add(two)) {
if (n.mod(i).equals(BigInteger.ZERO)) {
return false;
}
}
return true;
}

Method to check if number is symmetric in Java [duplicate]

This question already has answers here:
How do I check if a number is a palindrome?
(53 answers)
Closed 9 years ago.
I need help with a method to check if a number is symmetric, so from what I understand I need to check equality between all the numbers and to make sure there is no different number amounts them...right?
This is my code:
public boolean isSemetric (int number) {
int temp;
boolean answer = true;
while (number != 0) {
temp = number % 10;
number /= 10;
if (temp != (number%10)) {
answer = false;
} else {
answer = true;
}
}
return answer;
}
I'm kind of new to programming so be forgiven to my code :/
Thanks!
As peter.petrov pointed out in the comment section of your question, your method as it's written will always return false, except for when number is equal to 0. The reason for this can be seen when you pass in a number like 111 and step through the code in a debugger. The final iteration will fail because number /= 10 will result in 0, and temp will be 1, which fails your test.
If you are indeed looking to identify palindromes, consider the following approach that should be simple to implement
1. copy number into temp
2. convert temp to a String, and reverse it (tmpStr)
3. convert tmpStr back to an integer (reversedInt)
4. compare number and reversedInt for equality
viola. Not the most efficient algorithm, but its easy to understand and gets the job done.
I would do it like this (I don't want to use String here and I don't want to use local array variable for the digits).
public static boolean isSymmetric (long number) {
if (number == 0) return true;
else if (number < 0) return false;
long DEG_10 = (long)(Math.pow(10, (int)Math.log10(number)));
while (number > 0){
long dStart = number / DEG_10;
long dEnd = number % 10;
if (dStart != dEnd) return false;
number = (number - dStart * DEG_10 - dEnd) / 10;
DEG_10 /= 100;
}
return true;
}
This is the easiest approach I can think of - Get the String value of the number, if the reverse is the same then it is symmetrical.
// Symmetry
public static boolean isSymmetric(int number) {
String val = String.valueOf(number); // Get the string.
StringBuilder sb = new StringBuilder(val);
return (val.equals(sb.reverse().toString())); // if the reverse is the same...
}
Here's a somewhat fixed up version of your code. However, it checks if all numbers are the same, e.g. 5555 or 111. 11211 would return false.
public boolean areAllDigitsTheSame (int number) {
int temp;
boolean answer = true;
while (number >= 10) {
temp = number % 10;
number /= 10;
if (temp != (number%10)) {
return false
}
}
return true;
}
Edit: The C++ answer in the linked question works by constructing the reverse number gradually in the loop, and finally checking if they're the same. This is a similar to what you are doing.
Here's another version for fun:
public boolean isPalindrome (int number) {
int reversedNumber = 0;
while (number > 0) {
int digit = number % 10;
reversedNumber = reversedNumber*10 + digit;
if (reversedNumber == number) { // odd number of digits
return true;
}
number /= 10;
if (reversedNumber == number) { // even number of digits
return true;
}
}
return false;
}

Java Recursive Binomial Coeffecients using Linked Lists

There is a challenge problem in my compsci UIL class to use tail recursion to get a list of binomial coefficients for a given number . I think I am pretty close but I am having a hard time with base cases.
Following is my Code :
public static Cons binomial(int n)
{
return binomialb(n, null, 1);
}
public static Cons binomialb(int n, Cons last, int power)
{
if(n == power || n < 0)
{
return cons(1, null);
}
else if(last == null)
{
last = cons(1, cons(1, null));
return binomialb(n-1, last, power);
}
else
{
Cons lst = cons(1, null);
while(rest(last)!=null)
{
lst = cons((Integer)first(last)+(Integer)first(rest(last)), lst);
last = rest(last);
}
return binomialb(n-1,lst,power);
}
}
Right now I just get a list of (1).....
Your recursive call is always binomialb(n-1,something,power), so the only things that change are the first parameter, n, and the list. Your initial call has power = 1, so that will remain forever so. Now your first condition is
if (n == power || n < 0) {
return cons(1,null);
}
If you call it with n > 1 initially, the calls become binomialb(n-k,...,1) for k = 1, ..., n-1. Finally the call is binomialb(1,lotsOfWastedWork,1) which will happily return cons(1,null). If you initially call it with n < 1, the n < 0 will make it return the same after at most one recursive call, n = 1 immediately returns cons(1,null).
Whenever last is not null in a call, you should use it.

Categories

Resources