0

Hello there I am learning Java and after doing some tasks to learn recursion I was giving my self some exercises to learn it a bit more but now I am struggeling with some..

So the main Problem is that I dont know how I can multiply every element in an Array recursively when the elements in that array are object (Maybe there is at the end no difference if objects are in there or not). So the exercise I gave myself was: check if 1 / 3 is in the given Array. If Yes then multiply everything in that array with 2 / 1. This is Fraction:

 private int numerator;      // Zaehler
 private int denominator;    // Nenner

        public Fraction ( int num, int denom )
        {
            if ( denom != 0 )
            {
                if ( denom < 0 )
                {
                    numerator = -num;
                    denominator = -denom;
                }
                else
                {
                    numerator = num;
                    denominator = denom;
                }
                reduce();
            }
            else
            {
                // error: division by zero
                throw new IllegalArgumentException();
            }
        }

        public Fraction()
        {
            numerator = 0;
            denominator = 1;
        }

        public Fraction( int num )
        {
            numerator = num;
            denominator = 1;
        }

So I got it done by doing it with an for loop:

public static Fraction[] mulWithFor(Fraction[] arr)
        {
            for (int i = 0; i<arr.length; i++)
            {
                arr[i] = arr[i].multiply(new Fraction(2,1));
            }
            return arr;
        }

But thats not my Main goal I want to do it recursively so that was my approach:

public static Fraction[] mulAus(Fraction[] arr, int i)
        {
            if (i>= 0 && i<arr.length)
            {
                rekurMul(arr,i);
                //return mulAus(rekurMul(arr,i-1));
            }
            return arr;
        }

        public static Fraction rekurMul(Fraction[] arr, int i)
        {
            if (i>= 0 && i<arr.length)
            {
                return arr[i].multiply(new Fraction(2,1));
                return arr[i].multiply(new Fraction(2, 1)); // Does Not Work!!!
            }
            throw new IndexOutOfBoundsException();
        }

Maybe there is someone who can Help me! Thank you for your attention.

OK Thanks to @Chaï Sarfati and also to the others trying to help me out. I now know how to multiply recursive things in an Array! I used the Methods from @Chaï Sarfati but wrote an alternative method for his "oneThirdIsPresent" which is also a recursive method : So now my working code looks like this

 public static Fraction[] mulAus(Fraction[] arr)
        {
            if(contains(arr,arr.length-1,new Fraction(1,3)))
            {
                rekurMul(arr,0);
                return arr;
            }
            throw new IllegalArgumentException("1/3 does not exist in the Input-Array");
        }

        public static void rekurMul(Fraction[] arr, int i)
        {
            if(i == arr.length)
            {
                return ;
            }
            arr[i] = arr[i].multiply(new Fraction(2,1));
            rekurMul(arr,i+1);
        }

The Method to check if 1 / 3 exists in the given Array.

public static boolean contains(Fraction[] arr, int i, Fraction x)
        {
            if (i>= 0 && i < arr.length)
            {
                if (arr[i].equals(x))
                { return true;}
                else
                { return contains(arr, i-1,x); }
            }
            return false;
        }

I hope other People can learn from the code.. Maybe there are better solutions but I am just starting Programming so I dont know them for now. Bye

2 Answers2

0

Assuming you have a multiplyBy(Fraction f) method that works properly in you Fraction class. Moreover, it will be better (more readable, more time & space complexity saving) to do it iteratively. For the sake of the example, I would do like this:

First define:

private static boolean oneThirdIsPresent(Fraction[] arr){
    for (int i = 0; i < arr.length; i++) {
        if(arr[i].numerator == 1 && arr[i].denominator == 3) {
            return true;
        }
    }
    return false;
}

private static void recursivelyMultBy2(Fraction[] arr, int index){
    if(index == arr.length){
        return;
    }
    arr[index] = arr[index].multiplyBy(new Fraction(2));
    recursivelyMultBy2(arr, index+1);
}

In order to solve finally:

public static void multBy2IfOneThirdIsPresent(Fraction[] arr){
    if(oneThirdIsPresent(arr)){
        recursivelyMultBy2(arr, 0);
    }else{
        return;
    }
}
  • The multiplication works now like a charm! Ty but the "oneThirdIsPresent" Methode does everytime sending me a true.. I wrote in Fraction an .equals() here the code ``` public boolean equals( Fraction other ) { return numerator == other.numerator & denominator == other.denominator; } ``` So is that wrong? It sends all time 1. – ManuelHGN May 30 '19 at 15:41
  • Try to add a second '&' character next to your '&' (i.e write && instead of just &). Indeed, the & alone is used to perform bitwise operations and the && is used as a boolean operator (see https://stackoverflow.com/questions/5564410/what-is-the-difference-between-and-in-java). Apart from that, your "equals()" method logic seems correct ! – Chaï Sarfati Jun 01 '19 at 18:47
0

Here's a quick example of just the recursive multiplication part:

public static void main(String[] args)
{
    Fraction[] fractions = new Fraction[] {new Fraction(1,2), new Fraction(2,3), new Fraction(3,1)};

    System.out.println("Fractions:");
    for(Fraction f: fractions)
    {
        System.out.println(f);
    }

    System.out.println("Multiplying array by 2...");
    Fraction.mulAus(fractions, new Fraction(2, 1));
    for(Fraction f: fractions)
    {
        System.out.println(f);
    }
}

Modified Fraction Class (multiplication code at the bottom):

public class Fraction
{

        private int numerator;      // Zaehler
        private int denominator;    // Nenner

        public Fraction(int num, int denom)
        {
            if (denom != 0)
            {
                if (denom < 0)
                {
                    numerator = -num;
                    denominator = -denom;
                }
                else
                {
                    numerator = num;
                    denominator = denom;
                }
                reduce();
            }
            else
            {
                // error: division by zero
                //throw new IllegalArgumentException();
            }
        }

        private void reduce()
        {
            // ... 
        }

        public Fraction()
        {
            numerator = 0;
            denominator = 1;
        }

        public Fraction(int num)
        {
            numerator = num;
            denominator = 1;
        }

        public String toString()
        {
            return numerator + " / " + denominator;
        }

        public void MultiplyBy(Fraction F)
        {
            if (F != null)
            {
                numerator = numerator * F.numerator;
                denominator = denominator * F.denominator;
                reduce();
            }
        }

        public static void mulAus(Fraction[] arr, Fraction F)
        {
            if(arr != null && F != null)
            {
                rekurMul(arr, 0, F);
            }
        }

        private static void rekurMul(Fraction[] arr, int i, Fraction F)
        {
            arr[i].MultiplyBy(F);
            if (i < (arr.length - 1))
            {
                rekurMul(arr, ++i, F);
            }
        }

}

Output:

enter image description here

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40