import java.util.Arrays;

/** Class that holds all the loop unrolling code */
public class MyUnroll {
    /*
     *  Example A:  Unrolling.  
     *  A loop with a known number of iterations can be unrolled
     *  by repeating the loop body (includeing the loop variable 
     *  update) as many times as the loop repeats.
     */

    /**
     *  A simple counting-based enumerated loop.  
     *  It prints one line of a multiplication table
     */
    public static void multiplicationFacts(int n) {
        for (int i = 1; i < 5; i++) {
            System.out.print(i+" x "+n+" = "+(i*n)+"\t");
        }
        System.out.println("");
    }

    /**
     *  The loop unrolled.  
     *  It prints one line of a multiplication table
     */
    public static void multiplicationFactsUnrolled(int n) {
        int i = 1;
        System.out.print(i+" x "+n+" = "+(i*n)+"\t");
        i++;
        System.out.print(i+" x "+n+" = "+(i*n)+"\t");
        i++;
        System.out.print(i+" x "+n+" = "+(i*n)+"\t");
        i++;
        System.out.print(i+" x "+n+" = "+(i*n)+"\t");
        i++;
        System.out.println("");
    }

     /** 
      *  This function prints out the inverse mod 7 of a number,
      *  if it exists
      */
     public static void inverseMod7(int n) {
         for (int i = 0; i < 7; i++) {
             if (i*n%7 == 1) {
                 System.out.println("The inverse of "+n+" mod 7 is "+i);
             }
         }
     }

    /*
     *  Exercise 1
     *
     *  Unroll the loop below.
     */

     /** 
      *  This function prints out the inverse mod 7 of a number,
      *  if it exists
      */
     public static void inverseMod7Unrolled(int n) {
        int i = 0;
        if (i*n%7 == 1) {
            System.out.println("The inverse of "+n+" mod 7 is "+i);
        }
        i++;     
        if (i*n%7 == 1) {
            System.out.println("The inverse of "+n+" mod 7 is "+i);
        }
        i++;     
        if (i*n%7 == 1) {
            System.out.println("The inverse of "+n+" mod 7 is "+i);
        }
        i++;     
        if (i*n%7 == 1) {
            System.out.println("The inverse of "+n+" mod 7 is "+i);
        }
        i++;     
        if (i*n%7 == 1) {
            System.out.println("The inverse of "+n+" mod 7 is "+i);
        }
        i++;     
        if (i*n%7 == 1) {
            System.out.println("The inverse of "+n+" mod 7 is "+i);
        }
        i++;     
        if (i*n%7 == 1) {
            System.out.println("The inverse of "+n+" mod 7 is "+i);
        }
        i++;     
     }

    /*
     *  Example B:  Partial unrolling
     *
     *  Loops that execute for an unknown number of times 
     *  cannot be fully unrolled in advance.  However,
     *  it is possible to unroll a finite number of loop
     *  iterations at the beginning and/or the end.
     */

    /**
     *  A simple logically controlled loop.  
     *
     *  It counts the number of elements before the first
     *  appearance of the target.  If the target does not
     *  appear at all, returns the number of elements in 
     *  the array.
     *
     *  Because we don't know the number of elements in the
     *  array, this loop cannot be completely unrolled.
     *  However, we can partially unroll it.
     */
    public static int countBefore(int[] a, int target) {
        int i = 0;
        while ((i < a.length)&&(a[i]!=target)) {
            i++;
        }
        return i;
    }

    /**
     *  Two iterations of the loop unrolled.  
     *
     *  It counts the number of elements before the first
     *  appearance of the target.  If the target does not
     *  appear at all, returns the number of elements in 
     *  the array.
     */
    public static int countBeforeUnrolled(int[] a, int target) {
        int i = 0;
        if ((i < a.length)&&(a[i]!=target)) {
            i++;
            if ((i < a.length)&&(a[i]!=target)) {
                i++;
                while ((i < a.length)&&(a[i]!=target)) {
                    i++;
                }
            }
        }
        return i;
    }

     /**
      *  Checks whether a number is prime
      */
    public static boolean isPrime(int n) {
        int i = 2;
        while ((i < n)&&(n%i!=0)) {
            i++;
        }
        return (i==n);
    }

    /*
     *  Exercise 2
     *
     *  Unroll three iterations of the loop below.
     */

     /**
      *  Checks whether a number is prime
      */
    public static boolean isPrimeUnrolled(int n) {
        int i = 2;
        if ((i < n)&&(n%i!=0)) {
            i++;
            if ((i < n)&&(n%i!=0)) {
                i++;
                if ((i < n)&&(n%i!=0)) {
                    i++;
                    while ((i < n)&&(n%i!=0)) {
                        i++;
                    }
                }
            }
        }
        return (i==n);
    }

    /*
     *  Exercise 3
     *
     *  Unroll two iterations of the loop below.
     */

    /**
     *  Adds the index to each element.
     */
    public static void incrementByIndex(int[] a) {
        for (int i = 0; i < a.length; i++) {
            a[i] += i;
        }
    }

    /**
     *  Adds the index to each element.
     */
    public static void incrementByIndexUnrolled(int[] a) {
        int i = 0;
        if (i < a.length) {
            a[i] += i;
            i++;
            if (i < a.length) {
                a[i] += i;
                i++;
                while (i < a.length) {
                    a[i] += i;
                    i++;
                }
            }
        }
    }

    /*
     *  Example C:  Midpoint exit
     *
     *  Sometimes loops will not want to execute an entire loop body
     *  on either the first or last iterations.  One way to deal with
     *  this is to use a conditional within the loop to prevent the
     *  unwanted part from running when not appropriate.  Unfortunately
     *  the conditional must be checked one every iteration, even though
     *  it only applies once.  A better solution is to unroll the loop
     *  for the iteration in question and write only the code you want.
     *
     *  In this example, we want to print a comma-separated list of
     *  values.  Because the commas go between the elements, we don't 
     *  need one after the last element is printed.
     */

    /*
     *  Prints an array of int as a comma-separated list.
     *  This version uses a break, and also
     *  requires a conditional check on each iteration.
     */
    public static void printArrayVar1(int[] a) {
        System.out.print("{");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i]);
            if (i == a.length-1) {
                break;
            }
            System.out.print(", ");
        }
        System.out.println("}");
    }

    /*
     *  Prints an array of int as a comma-separated list.
     *  This version doesn't use a break but still requires
     *  the conditional check on each iteration.
     */
    public static void printArrayVar2(int[] a) {
        System.out.print("{");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i]);
            if (i != a.length-1) {
                System.out.print(", ");
            }
        }
        System.out.println("}");
    }

    /*
     *  Prints an array of int as a comma-separated list.
     *  Unrolls the last iteration for a more graceful implementation.
     *  Note that we could now combine the consecutive print statements
     *  into a single line if we wanted, for further refinement.
     */
    public static void printArrayUnrolled(int[] a) {
        System.out.print("{");
        for (int i = 0; i < a.length-1; i++) {
            System.out.print(a[i]);
            System.out.print(", ");
        }
        // we do need a check here in case the array is empty
        if (a.length > 0) {
            System.out.print(a[a.length-1]);
        }
        System.out.println("}");
    }

    /*
     *  We could just as easily view this task as a problem with the 
     *  first iteration instead of the last.  In other words, we want to
     *  print a comma BEFORE each element, except for the first one.
     */

    /*
     *  Prints an array of int as a comma-separated list.
     *  In this version the conditional checks for the
     *  first iteration rather than the last.
     */
    public static void printArrayVar3(int[] a) {
        System.out.print("{");
        for (int i = 0; i < a.length; i++) {
            if (i != 0) {
                System.out.print(", ");
            }
            System.out.print(a[i]);
        }
        System.out.println("}");
    }

    /*
     *  Exercise 4:  Partial unroll
     *
     *  Unroll the loop in printArrayVar3 to eliminate
     *  the conditional within the loop body.
     */

    /*
     *  Prints an array of int as a comma-separated list.
     */
    public static void printArrayVar3Unrolled(int[] a) {
        System.out.print("{");
        // we need a check here in case the array has no elements
        // but at least it only gets checked once.
        if (a.length > 0) {  
            System.out.print(a[0]);
        }
        for (int i = 1; i < a.length; i++) {
            System.out.print(", "+a[i]);
        }
        System.out.println("}");    }


    /*
     *  Prints an array of int as a comma-separated list, with "and"
     *  between the last two elements and no surrounding {}
     */
    public static void printArrayWithAnd(int[] a) {
        if (a.length == 1) {
            System.out.println(a[0]);
        } else if (a.length == 2) {
            System.out.println(a[0]+" and "+a[1]);
        } else {
            for (int i = 0; i < a.length; i++) {
                System.out.print(a[i]);
                if (i < a.length-2) {
                    System.out.print(", ");
                }
                if (i == a.length-2) {
                    System.out.print(", and ");
                }
            }
            System.out.println("");
        }
    }

    /*
     *  Exercise 5:  Multiple partial unroll
     *
     *  In this exercise we want to print the array with "and"
     *  between the last two elements.  Rewrite the function above
     *  so that it needs no conditionals.
     */

    /*
     *  Prints an array of int as a comma-separated list, with "and"
     *  between the last two elements and no surrounding {}
     */
    public static void printArrayWithAndUnrolled(int[] a) {
        if (a.length == 1) {
            System.out.println(a[0]);
        } else if (a.length == 2) {
            System.out.println(a[0]+" and "+a[1]);
        } else {
            for (int i = 0; i < a.length-2; i++) {
                System.out.print(a[i]+", ");
            }
            System.out.println(a[a.length-2]+", and "+a[a.length-1]);
        }  
    }

    /** Runs the lab */
    public static void main(String[] args) {
        System.out.println("When complete, output below should consist of pairs of identical lines:");
        multiplicationFacts(6);
        multiplicationFactsUnrolled(6);
        inverseMod7(6);
        inverseMod7Unrolled(6);
        int a[] = {4,2,5,1,2,6};
        System.out.println(countBefore(a,1));
        System.out.println(countBeforeUnrolled(a,1));
        System.out.println("97 is prime?  "+isPrime(97));
        System.out.println("97 is prime?  "+isPrimeUnrolled(97));
        incrementByIndex(a);
        System.out.println("Incremented:  "+Arrays.toString(a));
        int b[] = {4,2,5,1,2,6};
        incrementByIndexUnrolled(b);
        System.out.println("Incremented:  "+Arrays.toString(b));
        printArrayVar1(a);
        printArrayVar2(a);
        printArrayUnrolled(a);
        printArrayVar3(a);
        printArrayVar3Unrolled(a);
        printArrayWithAnd(a);
        printArrayWithAndUnrolled(a);
        int c[] = {9};
        printArrayWithAnd(c);
        printArrayWithAndUnrolled(c);
        int d[] = {3,2};
        printArrayWithAnd(d);
        printArrayWithAndUnrolled(d);
        int e[] = {4,8,7};
        printArrayWithAnd(e);
        printArrayWithAndUnrolled(e); 
    }
}